Implementing Interfaces Once an interface has been declared, it must be implemented in a class before it can be used. The interfaces
implemented by a class are specified in the class's declaration, after the name of the class's ancestor.
Class Declarations Such declarations have the form
type className = class (ancestorClass, interface1, ..., interfacen)
memberList
end;
For example,
type
TMemoryManager = class(TInterfacedObject, IMalloc, IErrorInfo)
.
.
.
end;
declares a class called
TMemoryManager
that implements the
IMalloc
and
IErrorInfo
interfaces. When a class
implements an interface, it must implement (or inherit an implementation of) each method declared in the interface.
Here is the (Win32) declaration of TInterfacedObject in the
System
unit. On the .NET platform, TInterfacedObject
is an alias for TObject.
type
TInterfacedObject = class(TObject, IInterface)
protected
FRefCount: Integer;
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
public
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
class function NewInstance: TObject; override;
property RefCount: Integer read FRefCount;
end;
TInterfacedObject implements the IInterface interface. Hence TInterfacedObject declares and implements each of
the three IInterface methods.
Classes that implement interfaces can also be used as base classes. (The first example above declares
TMemoryManager
as a direct descendent of TInterfacedObject.) On the Win32 platform, every interface inherits
from IInterface, and a class that implements interfaces must implement the
QueryInterface
,
_AddRef
, and
_Release
methods. The
System
unit's TInterfacedObject implements these methods and is thus a convenient base
from which to derive other classes that implement interfaces. On the .NET platform, IInterface does not declare these
methods, and you do not need to implement them.
When an interface is implemented, each of its methods is mapped onto a method in the implementing class that has
the same result type, the same calling convention, the same number of parameters, and identically typed parameters
195
in each position. By default, each interface method is mapped to a method of the same name in the implementing
class.