RAD Studio
ContentsIndex
PreviousUpNext
Using Interfaces Across the Hierarchy

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,

IPaint = interface
  procedure Paint;
end;

and the two classes,

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

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:

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

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

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.

Copyright(C) 2008 CodeGear(TM). All Rights Reserved.
What do you think about this topic? Send feedback!