ZetCode

Pascal interfaces

last modified November 19, 2026 Free Pascal 3.2.2

An interface describes a set of methods without providing their implementation. A class implements an interface by declaring it after the parent class and writing the method bodies. Code that depends on the interface does not need to know the class behind it, and one class can implement several interfaces, which gives Object Pascal a controlled form of multiple inheritance. This article starts with one interface and one class, then adds a second implementation, reference counting, GUIDs, interface inheritance, and delegation.

An interface is a contract

An interface type is declared with the keyword interface and ends with end. Its methods have signatures but no bodies. A class lists the interfaces it implements after its ancestor, as in TConsoleLogger = class(TInterfacedObject, ILogger). The first example has no GUID and no reference-counting details; it only shows the shape of a contract and one class that fulfills it.

intf1.pas
program intf1;
{$mode objfpc}{$H+}

type
  ILogger = interface
    procedure Log(const Msg: string);
  end;

  TConsoleLogger = class(TInterfacedObject, ILogger)
  public
    procedure Log(const Msg: string);
  end;

procedure TConsoleLogger.Log(const Msg: string);
begin
  WriteLn('[console] ', Msg);
end;

var
  L: ILogger;

begin
  L := TConsoleLogger.Create;
  L.Log('hello');
  L := nil;
  WriteLn('done');
end.

ILogger promises one method, Log. TConsoleLogger supplies the body, and L := TConsoleLogger.Create stores the object behind an interface reference. The call L.Log('hello') dispatches to the class method. An interface implicitly descends from IInterface, and TInterfacedObject implements the three lifetime methods that IInterface requires.

$ fpc -gl intf1.pas
$ ./intf1
[console] hello
done

A second implementation

The interface is useful when more than one class can satisfy it. The next program adds a second logger that frames each message with stars and a Run procedure that accepts the interface rather than a concrete class. Run contains no if or case: it calls the two methods that the contract guarantees.

intf2.pas
program intf2;
{$mode objfpc}{$H+}

type
  ILogger = interface
    procedure Log(const Msg: string);
  end;

  TConsoleLogger = class(TInterfacedObject, ILogger)
  public
    procedure Log(const Msg: string);
  end;

  TStarLogger = class(TInterfacedObject, ILogger)
  public
    procedure Log(const Msg: string);
  end;

procedure TConsoleLogger.Log(const Msg: string);
begin
  WriteLn('[console] ', Msg);
end;

procedure TStarLogger.Log(const Msg: string);
begin
  WriteLn('*** ', Msg, ' ***');
end;

procedure Run(const Logger: ILogger);
begin
  Logger.Log('starting');
  Logger.Log('finished');
end;

var
  L: ILogger;

begin
  L := TConsoleLogger.Create;
  Run(L);
  L := TStarLogger.Create;
  Run(L);
  L := nil;
  WriteLn('done');
end.

Both classes implement ILogger, so both can be passed to Run. Assigning a new object to L releases the reference to the previous one before the new value is stored, which is how the console logger disappears without an explicit Free. A third implementation could be added in another unit without changing Run or the interface.

$ fpc -gl intf2.pas
$ ./intf2
[console] starting
[console] finished
*** starting ***
*** finished ***
done

Reference counting and object lifetime

An interface reference is reference counted. Each assignment adds a reference, and each time a reference goes out of scope or is set to nil, the count drops. When the count reaches zero, the object behind the interface is freed. TInterfacedObject implements this bookkeeping, which is why the example classes descend from it rather than from TObject.

life2.pas
program life2;
{$mode objfpc}{$H+}

type
  IGreeter = interface
    procedure Greet;
  end;

  TGreeter = class(TInterfacedObject, IGreeter)
  public
    constructor Create;
    destructor Destroy; override;
    procedure Greet;
  end;

constructor TGreeter.Create;
begin
  WriteLn('created');
end;

destructor TGreeter.Destroy;
begin
  WriteLn('destroyed');
  inherited Destroy;
end;

procedure TGreeter.Greet;
begin
  WriteLn('hello');
end;

var
  G: IGreeter;

begin
  G := TGreeter.Create;
  G.Greet;
  G := nil;
  WriteLn('after nil');
end.

Setting G to nil releases the last reference, so the destructor runs before the next line. There is no Free call: an interface reference owns its object through the count, and freeing the object manually while references exist would leave them dangling. Mixing object references and interface references to the same instance is therefore a common source of double frees.

$ fpc -gl life2.pas
$ ./life2
created
hello
destroyed
after nil

GUIDs and Supports

The GUID in square brackets identifies the interface at run time. It makes it possible to ask an object whether it implements a particular interface. Supports(Ref, IWriter) returns a Boolean, and the three-argument form also returns the interface reference. This is the interface equivalent of is and as: the query is checked, and a failed cast does not corrupt the program.

intfcast.pas
program intfcast;
{$mode objfpc}{$H+}

uses SysUtils;

type
  IReader = interface
  ['{11111111-1111-1111-1111-111111111111}']
    function ReadText: string;
  end;

  IWriter = interface
  ['{22222222-2222-2222-2222-222222222222}']
    procedure WriteText(const S: string);
  end;

  TDevice = class(TInterfacedObject, IReader, IWriter)
  private
    FText: string;
  public
    function ReadText: string;
    procedure WriteText(const S: string);
  end;

function TDevice.ReadText: string;
begin
  Result := FText;
end;

procedure TDevice.WriteText(const S: string);
begin
  FText := S;
end;

var
  Device: TDevice;
  R: IReader;
  W: IWriter;

begin
  Device := TDevice.Create;
  R := Device;
  W := Device;
  W.WriteText('hello');
  WriteLn('read: ', R.ReadText);
  WriteLn('R supports IWriter: ', Supports(R, IWriter));
  if Supports(R, IWriter, W) then
  begin
    W.WriteText('changed');
    WriteLn('read: ', R.ReadText);
  end;
end.

TDevice implements both interfaces, so the same object can be reached through either one. The two references R and W share the object and increase its reference count. The Supports call asks the object behind R for its IWriter side and stores that in W; the write is then visible through R because both interfaces point at the same fields. A GUID must be unique; the values in the examples are fixed only so that the output is reproducible.

$ fpc -gl intfcast.pas
$ ./intfcast
read: hello
R supports IWriter: TRUE
read: changed

Interface inheritance

One interface can extend another. IExtended = interface(IBase) contains all methods of IBase plus its own, and a class that implements IExtended must implement both sets. An IExtended reference can be assigned to an IBase variable, because every extended interface is also a base interface.

intfinherit.pas
program intfinherit;
{$mode objfpc}{$H+}

type
  IBase = interface
  ['{55555555-5555-5555-5555-555555555555}']
    procedure Ping;
  end;

  IExtended = interface(IBase)
  ['{66666666-6666-6666-6666-666666666666}']
    procedure Pong;
  end;

  TBoth = class(TInterfacedObject, IExtended)
  public
    procedure Ping;
    procedure Pong;
  end;

procedure TBoth.Ping;
begin
  WriteLn('ping');
end;

procedure TBoth.Pong;
begin
  WriteLn('pong');
end;

var
  E: IExtended;
  B: IBase;

begin
  E := TBoth.Create;
  E.Ping;
  E.Pong;
  B := E;
  B.Ping;
end.

The class lists only IExtended, yet it implements Ping as well, because the extended interface includes it. The assignment B := E is an upcast and needs no cast operator. Going the other way, from IBase to IExtended, requires a Supports query or an as cast, since the object may implement only the base interface.

$ fpc -gl intfinherit.pas
$ ./intfinherit
ping
pong
ping

Delegation with implements

A class can forward an interface to an inner object instead of implementing every method itself. The property property Inner: ILogger read FInner implements ILogger; tells the compiler to answer ILogger calls by calling the same methods on FInner. A wrapper can implement other interfaces itself and delegate this one unchanged.

delegate.pas
program delegate;
{$mode objfpc}{$H+}

type
  ILogger = interface
  ['{33333333-3333-3333-3333-333333333333}']
    procedure Log(const Msg: string);
    function GetCount: Integer;
    property Count: Integer read GetCount;
  end;

  TBaseLogger = class(TInterfacedObject, ILogger)
  private
    FCount: Integer;
  public
    procedure Log(const Msg: string);
    function GetCount: Integer;
  end;

  TWrapper = class(TInterfacedObject, ILogger)
  private
    FInner: ILogger;
  public
    constructor Create(AInner: ILogger);
    property Inner: ILogger read FInner implements ILogger;
  end;

procedure TBaseLogger.Log(const Msg: string);
begin
  Inc(FCount);
  WriteLn('[base] ', Msg);
end;

function TBaseLogger.GetCount: Integer;
begin
  Result := FCount;
end;

constructor TWrapper.Create(AInner: ILogger);
begin
  FInner := AInner;
end;

var
  L: ILogger;

begin
  L := TWrapper.Create(TBaseLogger.Create);
  L.Log('first');
  L.Log('second');
  WriteLn('count = ', L.Count);
end.

TWrapper has no Log method of its own. The compiler generates forwarding methods that call FInner, including the property getter. The inner interface is kept alive by the wrapper's field, so it lives as long as the wrapper. Delegation is useful for adapters, decorators, and for combining several small implementations behind one interface.

$ fpc -gl delegate.pas
$ ./delegate
[base] first
[base] second
count = 2

Interfaces and classes together

An interface has no fields and no constructor, so it cannot hold state on its own. The state lives in the implementing class, and the interface only exposes the operations. A class can implement any number of interfaces, which is how Object Pascal avoids the diamond problem of multiple class inheritance: the class has one ancestor chain, and several independent contracts.

An interface reference is not an object reference. is and as work with interfaces in Free Pascal, but the reliable way to move between interface types is Supports. Calling Free on an interface is a compile-time error, because the reference count owns the object. The inheritance article covers the class side of these relationships, and the classes article explains the constructors and destructors that interfaces rely on.

Next steps

The generics article parameterizes classes and routines by type, and the pointers article looks at the manual memory model that reference counting replaces. The error handling article explains what happens when a method behind an interface raises.

Source

Free Pascal Reference guide

Free Pascal: interfaces

Pascal on Wikipedia

In this article we declared an interface, implemented it in two classes, passed it to a procedure, followed reference counting, queried objects with Supports, extended an interface, and delegated one to an inner object. The series continues with Pascal generics.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Pascal tutorials.