Contents | Prev | Next | Index


Virtual Methods

A method can be made virtual by including a VIRTUAL keyword in its declaration. When a virtual method is called, the method resolution determines the actual run-time type of the class or object for finding the correct target method to activate.

Example of a virtual method declaration:

TYPE
  TFigure = CLASS
    PROCEDURE Draw; VIRTUAL;
    :
  END;

A virtual method can be overriden in a descendant class. When an OVERRIDE keyword is included in the declaration of a method, the method overrides the inherited implementation of the method. Order and types of the overriding method must exactly match with those of the inherited virtual method. The same is true for a function result type (if any).

The only way a virtual method can be overridden is through the OVERRIDE keyword. Notice that, unlike other Pascal compilers such as Borland Object Pascal, an inherited virtual method, if redeclared in a descendant class, must be overridden, it cannot be hidden by omitting the OVERRIDE specifier. This restriction applies because of the way Java implements virtual methods. An inherited static method cannot be overridden.

Example for method overriding:

TYPE
  TRectangle = CLASS( TFigure )
    PROCEDURE Draw; OVERRIDE;
    :
  END;
  TEllipse = CLASS( TFigure )
    PROCEDURE Draw; OVERRIDE;
    :
  END;

The following section of code illustrates the effect of calling a virtual method through a class type variable whose actual type varies at runtime:

VAR
  Figure : TFigure;
BEGIN
  Figure := NEW( TRectangle );
  Figure.Draw; {invokes TRectangle.Draw}
  DISPOSE( Figure );
  Figure := NEW( TEllipse );
  Figure.Draw; {invokes TEllipse.Draw}
  DISPOSE( Figure );
END;


Contents | Prev | Next | Index

Canterbury Pascal for JVM  (Last documentation update Sep 02, 2004)
Copyright © 1999-2004 J.Neuhoff - mhccorp.com  . All rights reserved.
Please send any comments or corrections to neuhoff@mhccorp.com