Interfaces in Pascal
In Pascal, interfaces are not a built-in language feature like in some other languages. However, we can simulate the concept using abstract classes. Here’s how we can implement the geometry example:
In this Pascal example, we define an abstract base class TGeometry
that serves as our interface. It declares two abstract methods: Area
and Perimeter
.
We then implement this “interface” for rectangles (TRect
) and circles (TCircle
). Each of these classes inherits from TGeometry
and provides concrete implementations for the Area
and Perim
methods.
The Measure
procedure takes a TGeometry
parameter, allowing it to work with any object that inherits from TGeometry
. This demonstrates polymorphism, which is similar to interface usage in other languages.
In the main
part of the program, we create instances of TRect
and TCircle
, and pass them to the Measure
procedure.
To run this program, save it as Interfaces.pas
and compile it with a Pascal compiler. For example, using Free Pascal:
This will output:
Note that in Pascal, we need to manually manage memory for objects. That’s why we call Free
on our objects at the end of the program. In languages with garbage collection, this step would not be necessary.
This example demonstrates how to implement interface-like behavior in Pascal using abstract classes and inheritance.