Static Methods
Methods are by default static. When a static method is called, the declared (compile-time) type of the class or object
variable used in the method call determines which implementation to activate. In the following example, the
Draw
methods are static.
type
TFigure =
class
procedure Draw;
end;
TRectangle = class(TFigure)
procedure Draw;
end;
Given these declarations, the following code illustrates the effect of calling a static method.
In the second call to
Figure.Draw
, the
Figure
variable references an object of class
TRectangle
,
but the call invokes the
implementation of
Draw
in
TFigure
, because the declared type of the
Figure
variable is
TFigure
.
var
Figure: TFigure;
Rectangle: TRectangle;
begin
Figure := TFigure.Create;
Figure.Draw; // calls TFigure.Draw
Figure.Destroy;
Figure := TRectangle.Create;
Figure.Draw; // calls TFigure.Draw
TRectangle(Figure).Draw; // calls TRectangle.Draw
Figure.Destroy;
Rectangle := TRectangle.Create;
Rectangle.Draw; // calls TRectangle.Draw
Rectangle.Destroy;
end;
Dostları ilə paylaş: