Working Delphi 2009 Override Example
The following code assumes a Windows application with a single form�with a button. It�demonstrates using virtual and override to override a parent method in a descendant class.
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
end;
TRobot = class(TObject)
public
procedure Speak; virtual;
end;
TCyborg = class(TRobot)
procedure Speak; override;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TRobot.Speak;
begin
ShowMessage('Robot says hi');
end;
procedure TCyborg.Speak;
begin
ShowMessage('Cyborg says hi');
end;
procedure TForm1.Button1Click(Sender: TObject);
var
Robot: TRobot;
Cyborg: TCyborg;
begin
Robot := TRobot.Create;
Cyborg := TCyborg.Create;
Robot.Speak;
Cyborg.Speak;
FreeAndNil(Robot);
FreeAndNil(Cyborg);
end;
end.
Hiding a Method with 'reintroduce'
Use the reintroduce keyword to introduce a new implementation of a parent method (this hides the parent method). You can hide a method without using�reintroduce but you will get a compiler warning. Using�reintroduce will suppress the warning.
The�reintroduce and override modifiers have different meanings. The�reintroduce modifier creates a new member with the same name, signature, and visibility and hides the original member. The override modifier extends the implementation for an inherited member and allows you to implement inheritance-based polymorphism.
Avoid Introducing New Members: Sometimes there are clear reasons to introduce a new method with the same name, signature, and visibility of a parent method. In those clear cases, introducing a new member is a powerful feature. However, if you do not have a clear reason, then avoid introducing a new version of a method by naming the new method something unique and appropriate.
//interface section:
TRobot = class(TObject)
public
procedure Speak;
end;
TCyborg = class(TRobot)
procedure Speak; reintroduce;
end;
//implementation section:
procedure TRobot.Speak;
begin
ShowMessage('Robot says hi');
end;
procedure TCyborg.Speak;
begin
ShowMessage('Cyborg says hi');
end;
Invoking the Parent Method with 'inherited'
A common task In OO is to extend a method by first executing the parent method code and then adding code. Use the Inherited keyword to invoke the parent class method.
method Robot.Speak;
begin
MessageBox.Show("Robot says hi");
end;
method Cyborg.Speak;
begin
inherited;
MessageBox.Show("Cyborg says hi");
end;