多态性赋值能力
时间:2011-03-21 来源:ManLoveGirls
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TParent = class(TObject)
procedure Draw;virtual;
end;
TChild = class(TParent)
procedure Draw;override;
procedure ShowHierarchy ;virtual;
end;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TParent }
procedure TParent.Draw;
begin
ShowMessage('ParentDraw');
end;
{ TChild }
procedure TChild.Draw;
begin
ShowMessage('ChildDraw');
end;
procedure TChild.ShowHierarchy;
begin
ShowMessage('Child show hierarchy');
end;
procedure ChildDraw(O:TParent);
begin
o.Draw;
end;
procedure FreeObject(O:TObject);
begin
O.Free;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
Parent:TParent;
Child :TChild;
begin
Parent := TParent.Create;
Child :=TChild.Create;
ChildDraw(Parent);
ChildDraw(Child);
FreeObject(Child);
FreeObject(parent);
end;
end.
注意:
不能将子对象赋值给父对象,因为子对象大于它的父对象。也就是说,子对象有更多的方法和域 例如:你可以用为三层楼准备的材料来建筑两层楼
但不能用为两层楼准备的材料来建筑三层楼
上面的代码中:
Child := Parent;//不要这样做,因为Parent没有ShowHierarchy方法
Parent := Child;//正确
TParent的所有函数都是TChild的一部分,不属于TParent中的方法被忽略
相关阅读 更多 +
排行榜 更多 +