Virtual and Dynamic Methods

To make a method virtual or dynamic, include the virtual or dynamic directive in its declaration. Virtual and dynamic methods, unlike static methods, can be overridden in descendant classes. When an overridden method is called, the actual (runtime) type of the class or object used in the method callnot the declared type of the variabledetermines which implementation to activate.

To override a method, redeclare it with the override directive. An override declaration must match the ancestor declaration in the order and type of its parameters and in its result type (if any).

In the following example, the Draw method declared in TFigure is overridden in two descendant classes.

type

TFigure = class procedure Draw; virtual; end;

TRectangle = class(TFigure) procedure Draw; override; end;

TEllipse = class(TFigure)

procedure Draw; override; end;

Given these declarations, the following code illustrates the effect of calling a virtual method through a variable whose actual type varies at runtime.

Figure: TFigure; begin

Figure := TRectangle.Create;

  1. Draw; // calls TRectangle.Draw
  2. Destroy;

Figure := TEllipse.Create;

  1. Draw; // calls TEllipse.Draw
  2. Destroy; end;

Only virtual and dynamic methods can be overridden. All methods, however, can be overloaded; see Overloading methods.

The Delphi for .NET compiler supports the concept of a final virtual method. When the keyword final is applied to a virtual method, no ancestor class can override that method. Use of the final keyword is an important design decision that can help document how the class is intended to be used. It can also give the .NET JIT compiler hints that allow it to optimize the code it produces.

Project Management Made Easy

Project Management Made Easy

What you need to know about… Project Management Made Easy! Project management consists of more than just a large building project and can encompass small projects as well. No matter what the size of your project, you need to have some sort of project management. How you manage your project has everything to do with its outcome.

Get My Free Ebook


Post a comment