Interface Keyword
unitName
; interfaceDeclarations
... implementationDeclarations
... end. typeName
= interface ... end; typeName
= interface(BaseInterface
, ...) ... end;
The interface
keyword serves two entirely
unrelated functions.
The most common use for interface
is to start the
interface section of a unit. Every unit must have an interface
section, although it can be empty. Declarations in an interface
section are exported and can be used by any other unit that uses the
unit.
The second use is to declare an interface type. An interface defines an abstract protocol that can be implemented by a class. An interface can have method and property declarations, but no field declarations. All interface declarations are public.
The uses
declaration, if it is present, must be
the first declaration in the interface section.
Every function, procedure, and non-abstract method declared in the interface section must be defined in the implementation section. The parameter names and types in the definitions must match the declarations in the interface section.
Although interfaces look and act like COM interfaces, you are not restricted to using COM. Interfaces are a powerful and underused technique for writing object-oriented code. Interfaces feature automatic memory management and increased polymorphism. Chapter 2, discusses this topic at length.
Delphi automatically type casts an interface reference to a GUID when
necessary. Thus, you can use an interface name in a call to
QueryInterface
, e.g.:
var Stream: IStream; begin if Something.QueryInterface(IStream, Stream) = S_OK then Stream.Revert;