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:

program Interfaces;

uses
  Math, SysUtils;

type
  TGeometry = class
  public
    function Area: Double; virtual; abstract;
    function Perim: Double; virtual; abstract;
  end;

  TRect = class(TGeometry)
  private
    FWidth, FHeight: Double;
  public
    constructor Create(Width, Height: Double);
    function Area: Double; override;
    function Perim: Double; override;
  end;

  TCircle = class(TGeometry)
  private
    FRadius: Double;
  public
    constructor Create(Radius: Double);
    function Area: Double; override;
    function Perim: Double; override;
  end;

constructor TRect.Create(Width, Height: Double);
begin
  FWidth := Width;
  FHeight := Height;
end;

function TRect.Area: Double;
begin
  Result := FWidth * FHeight;
end;

function TRect.Perim: Double;
begin
  Result := 2 * FWidth + 2 * FHeight;
end;

constructor TCircle.Create(Radius: Double);
begin
  FRadius := Radius;
end;

function TCircle.Area: Double;
begin
  Result := Pi * FRadius * FRadius;
end;

function TCircle.Perim: Double;
begin
  Result := 2 * Pi * FRadius;
end;

procedure Measure(G: TGeometry);
begin
  WriteLn(G.ClassName);
  WriteLn(Format('Area: %.2f', [G.Area]));
  WriteLn(Format('Perimeter: %.2f', [G.Perim]));
  WriteLn;
end;

var
  R: TRect;
  C: TCircle;

begin
  R := TRect.Create(3, 4);
  C := TCircle.Create(5);

  Measure(R);
  Measure(C);

  R.Free;
  C.Free;
end.

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:

$ fpc Interfaces.pas
$ ./Interfaces

This will output:

TRect
Area: 12.00
Perimeter: 14.00

TCircle
Area: 78.54
Perimeter: 31.42

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.