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;
缺省情况下,方法是静态的。当一个静态方法被调用时,方法调用中使用的类或对象变量,其编译时声明的类型决定了哪一个实现是有效的。下面的例子中,Draw方法是静态的。
type
TFigure = class
procedure Draw;
end;
TRectangle = class(TFigure)
procedure Draw;
end;
对于上面给出的声明,下面的代码举例说明了调用静态方法的效果。在第二次调用Figure.Draw中,Figure变量引用了TRectangle类的对象,但是调用中实际上调用的是TFigure类中的Draw方法,因为Figure变量声明的类型是TFigure。
var
Figure: TFigure;
Rectangle: TRectangle;
begin
Figure := TFigure.Create;
Figure.Draw; //调用的是TFigure.Draw
Figure.Destroy;
Figure := TRectangle.Create;
Figure.Draw; //调用的是TFigure.Draw
TRectangle(Figure).Draw; //调用的是TRectangle.Draw
Figure.Destroy;
Rectangle := TRectangle.Create;
Rectangle.Draw; //调用的是TRectangle.Draw
Rectangle.Destroy;
end;