随笔 - 2146  文章 - 97 评论 - 11767 trackbacks - 253

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs;

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

//夫类
  TParent = class
  protected
    function MyFun(i: Integer): Integer; dynamic;  //动态方法
    procedure MyProc; virtual;  //虚方法
  end;

//子类
  TChild = class(TParent)
  protected
    function MyFun(i: Integer): Integer; override;  //覆盖
    procedure MyProc; override;  //覆盖
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

{ TParent }

function TParent.MyFun(i: Integer): Integer;
begin
  Inc(i);
  Result := i;
end;

procedure TParent.MyProc;
begin
  ShowMessage('Parent');
end;

{ TChild }

function TChild.MyFun(i: Integer): Integer;
begin
  i := inherited MyFun(i);  //先调用夫类方法,被 +1;当然可以不调用
  Inc(i);                   //子类再 +1
  Result := i;
end;

procedure TChild.MyProc;
begin
  inherited;  //先调用夫类方法;当然可以不调用
  ShowMessage('Child');
end;

//测试
procedure TForm1.FormCreate(Sender: TObject);
var
  p: TParent;
  c: TChild;
begin
  p := TParent.Create;
  c := TChild.Create;

  p.MyProc;  //Parent
  c.MyProc;  //Parent; TChild

  ShowMessage(IntToStr(p.MyFun(2)));  //3
  ShowMessage(IntToStr(c.MyFun(2)));  //4

  p.Free;
  c.Free;
end;

end.
posted on 2007-12-05 15:02  万一  阅读(...)  评论(...编辑  收藏