Go Up to Using the object model Index
Delphi is a single-inheritance language. That means that any class has only a single direct ancestor. However, there are times you want a new class to inherit properties and methods from more than one base class so that you can use it sometimes like one and sometimes like the other. Interfaces let you achieve something like this effect.
An interface is like a class that contains only abstract methods (methods with no implementation) and a clear definition of their functionality. Interface method definitions include the number and types of their parameters, their return type, and their expected behavior. By convention, interfaces are named according to their behavior and prefaced with a capital I. For example, an IMalloc interface would allocate, free, and manage memory. Similarly, an IPersist interface could be used as a general base interface for descendants, each of which defines specific method prototypes for loading and saving the state of an object to a storage, stream, or file.
An interface has the following syntax:
IMyObject = interface procedure MyProcedure; end;
A simple example of an interface declaration is:
type IEdit = interface procedure Copy; procedure Cut; procedure Paste; function Undo: Boolean; end;
Interfaces can never be instantiated. To use an interface, you need to obtain it from an implementing class.
To implement an interface, define a class that declares the interface in its ancestor list, indicating that it will implement all of the methods of that interface:
TEditor = class(TInterfacedObject, IEdit) procedure Copy; procedure Cut; procedure Paste; function Undo: Boolean; end;
While interfaces define the behavior and signature of their methods, they do not define the implementations. As long as the class's implementation conforms to the interface definition, the interface is fully polymorphic, meaning that accessing and using the interface is the same for any implementation of it.