// inherited 就是调用父类方法的一个特殊命令; 举例:
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;
{ 建立父类, 类中包括一个函数 Fun 和一个等待覆盖的虚方法 Proc}
TBass = class
procedure Proc; virtual;
function Fun(x,y: Integer): string;
end;
{ 建立四个子类, 分别覆盖父类的虚方法}
TChild1 = class(TBass)
procedure Proc; override;
end;
TChild2 = class(TBass)
procedure Proc; override;
end;
TChild3 = class(TBass)
procedure Proc; override;
end;
TChild4 = class(TBass)
procedure Proc; override;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TBass }
function TBass.Fun(x, y: Integer): string;
begin
Result := IntToStr(x + y); { 父类函数是返回两个数的和}
end;
procedure TBass.Proc;
begin
ShowMessage('TBass'); 父类的虚方法会弹出信息: TBass}{
end;
{ TChild1 }
procedure TChild1.Proc;
begin
inherited Proc; 调用父类的 Proc 方法}{
end;
{ TChild2 }
procedure TChild2.Proc;
begin
inherited; 调用父类的同名方法可以省略方法名}{
ShowMessage('TChild2'); 然后弹出自己的信息框}{
end;
{ TChild3 }
procedure TChild3.Proc;
begin
ShowMessage('TChild3'); 先弹出自己的信息框}{
inherited; 再调用父类的同名方法}{
end;
{ TChild4 }
procedure TChild4.Proc;
begin
ShowMessage(inherited Fun(11,22)); { 调用父类的那个求和的函数}
end;
{测试}
procedure TForm1.Button1Click(Sender: TObject);
var
c1: TChild1;
c2: TChild2;
c3: TChild3;
c4: TChild4;
begin
c1 := TChild1.Create;
c2 := TChild2.Create;
c3 := TChild3.Create;
c4 := TChild4.Create;
c1.Proc; { 显示: TBass}
c2.Proc; { 先显示: TBass;再显示: TChild2}
c3.Proc; { 先显示: TChild3; 再显示: TBass}
c4.Proc; { 显示: 33; 11+22=33吗}
c1.Free;
c2.Free;
c3.Free;
c4.Free;
end;