RAD Studio |  |

Using Interfaces Across the Hierarchy
See Also
Collapse All

Using interfaces lets you separate the way a class is used from the way it is implemented. Two classes can implement the same interface without descending from the same base class. By obtaining an interface from either class, you can call the same methods without having to know the type of the class. This polymorphic use of the same methods on unrelated objects is possible because the objects implement the same interface. For example, consider the interface,

Copy Code

    IPaint = interface
      procedure Paint;
    end;

and the two classes,

Copy Code

    TSquare = class(TPolygonObject, IPaint)
      procedure Paint;
    end;
    TCircle = class(TCustomShape, IPaint)
      procedure Paint;
    end;

Whether or not the two classes share a common ancestor, they are still assignment compatible with a variable of IPaint as in

Copy Code

    var
      Painter: IPaint;
    begin
      Painter := TSquare.Create;
      Painter.Paint;
      Painter := TCircle.Create;
      Painter.Paint;
    end;

This could have been accomplished by having TCircle and TSquare descend from a common ancestor (say, TFigure), which declares a virtual method Paint. Both TCircle and TSquare would then have overridden the Paint method. In the previous example, IPaint could be replaced by TFigure. However, consider the following interface:

Copy Code

    IRotate = interface
      procedure Rotate(Degrees: Integer);
    end;

IRotate makes sense for the rectangle but not the circle. The classes would look like

Copy Code

    TSquare = class(TRectangularObject, IPaint, IRotate)
      procedure Paint;
      procedure Rotate(Degrees: Integer);
    end;
    TCircle = class(TCustomShape, IPaint)
      procedure Paint;
    end;

Later, you could create a class TFilledCircle that implements the IRotate interface to allow rotation of a pattern that fills the circle without having to add rotation to the simple circle.

Note: For these examples, the immediate base class or an ancestor class is assumed to have implemented the methods of IInterface, the base interface from which all interfaces descend. For more information on IInterface, see Implementing IInterface and Memory management of interface objects.
See Also

Using Interfaces with Procedures

Using the As Operator with Interfaces

Reusing Code and Delegation

Memory Management of Interface Objects

Using Interfaces in Distributed Applications

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!