Sometimes, the methods of an interface are implemented by a helper (or delegate) object, or the class instance has obtained an interface pointer for this interface and that should be used. This can be for instance when an interface must be added to a series of totally unrelated classes: the needed interface functionality is added to a separate class, and each of these classes uses an instance of the helper class to implement the functionality.
In such a case, it is possible to instruct the compiler that the interface is not implemented by the object itself, but actually resides in a helper class or interface. This can be done with the implements property modifier.
If the class has a pointer to the desired interface, the following will instruct the compiler that when the IMyInterface interface is requested, it should use the reference in the field:
The interface should not necessarily be in a field, any read identifier can be used.
If the interface is implemented by a delegate object, (a helper object that actually implements the interface) then it can be used as well with the implements keyword:
Note that in difference with Delphi, the delegate class must explicitly specify the interface: the compiler will not search for the methods in the delegate class, it will simply check if the delegate class implements the specified interface.
It is not possible to mix method resolution and interface delegation. That means, it is not possible to implement part of an interface through method resolution and implement part of the interface through delegation. The following attempts to implement IMyInterface partly through method resolution (P1), and partly through delegation. The compiler will not accept the following code:
The compiler will throw an error:
However, it is possible to implement one interface through method resolution, and another through delegation: