What is polymorphism? My understanding is that the same method will have different implementations in different objects, that's all.
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
end;
Three classes are defined, and the second two classes inherit from the first class Tbass TBass = class
procedure alert; virtual;
{With the virtual designator, this method may be modified (or overwritten)}
{This method is called a virtual method} end;
TChild1 = class(TBass)
procedure alert; override; {override 表示修改父类的同名方法}
end;
TChild2 = class(TBass)
procedure alert; override;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TBass }
procedure TBass.alert;
begin
ShowMessage('is Bass'); {同一个方法, 在不同类里有不同的实现}
end;
{ TChild1 }
procedure TChild1.alert;
begin
ShowMessage('is TChild1'); {同一个方法, 在不同类里有不同的实现}
end;
{ TChild2 }
procedure TChild2.alert;
begin
ShowMessage('is TChild2'); {同一个方法, 在不同类里有不同的实现}
end;
Test 1:procedure TForm1.Button1Click(Sender: TObject);
var
bass: TBass; {定义 TBass 的变量}
begin
bass := TBass.Create;
bass.alert; {is Bass}
bass.Free;
end;
Test 2:procedure TForm1.Button2Click(Sender: TObject);
var
bass: TBass; {注意还是定义 TBass 的变量}
begin
bass := TChild1.Create; {但这里是通过 TChild1 建立对象}
bass.alert; {is TChild1}
bass.Free;
end;
Test 3:procedure TForm1.Button3Click(Sender: TObject);
var
bass: TBass; {注意还是定义 TBass 的变量}
begin
bass := TChild2.Create; {但这里是通过 TChild2 建立对象}
bass.alert; {is TChild2}
bass.Free;
end;
{Summary: Now the same is the Bass.alert method, through the implementation of different objects, with different functions, this is polymorphism!}
End.