抽象类


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; virtual; abstract;

    //抽象方法(纯虚方法),只有定义没有实现,一个类包含一个即成抽象类,抽象类不能直接创建对象。

  end;



//子类

  TChild = class(TParent)

  protected

    function MyFun(i: Integer): Integer; override;  //覆盖

  end;



var

  Form1: TForm1;



implementation



{$R *.dfm}



{ TChild }



function TChild.MyFun(i: Integer): Integer;

begin

  Inc(i);

  Result := i;

end;



//测试

procedure TForm1.FormCreate(Sender: TObject);

var

  p: TParent;

  c: TChild;

begin

  p := TChild.Create;  //抽象类只能通过其子类创建对象

  c := TChild.Create;



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

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



  p.Free;

  c.Free;

end;



end.

你可能感兴趣的:(抽象类)