|
Text:=''''right''''; end;
{ Tson }
function Tson.throwhand: string;
begin Form1.edit2.Text:=''''left''''; end;
//这是对函数的调用:
procedure TForm1.Button1Click(Sender: TObject);
var FatherUse:Tfather; SonUse:Tson;
begin
FatherUse:=Tfather.Create;
SonUse:=Tson.Create;
FatherUse.throwhand;
SonUse.throwhand;
FatherUse.Free;
SonUse.Free;
end;
这是效果图:

我们看到,父类被一个叫virtual的关键字所修饰。这是何故?不加行吗?当然不行,原因就是前面所述,Delphi的方法都是静态的。我们知道,Java中,被修饰成abstract 或final的方法是不能被覆盖的。由此可知,Delphi的默认的静态方法也不能被覆盖。因此,Delphi定义了两个关键字:virtual(虚拟)和dynamic(动态)。它们让函数和过程成为动态的,用于后关联。Virtual和dynamic作用大致相同。只是virtual的方法较dynamic的方法在VMT中占用空间较大,而执行时间较短。这是因为,子类在override父类中的某一个virtual方法时,VMT会为子类提供未被voerride的其它父类的virtual方法。而dynamic则只提供被override的方法。这两个方式个有好处,在Delphi中常被一起使用。
嗯,再多想想。如果父类的一个virtual方法不但要被子类方法override,还要被同一个类中的同名方法overload,那要怎么做呢?看看下面的例子:
type
Tfather=class
public //多了关键字overload function throwhand:string; overload;virtual;
function throwhand(m:integer):integer; overload;virtual;
end;
type
Tson=class(Tfather)
public //多了关键字reintroduce,我发现不用它也行。但建议使用。
function throwhand:string;reintroduce;override;
end;
我们再来看看实现部分:
{ Tfather }
function Tfather.throwhand: string;
begin
result:=''''right'''';
end;
function Tfather.throwhand(m: integer): integer;
begin
result:=m;
end;
{ Tson }
function Tson.throwhand: string;
begin
Form1.edit2.Text:=''''left'''';
end;
这是调用部分:
procedure TForm1.Button1Click(Sender: TObject);
var
FatherUse:Tfather;
SonUse:Tson;
begin
FatherUse:=Tfather.Create;
SonUse:=Tson.Create;
Form1.edit1.Text:=''''usehand:''''+FatherUse.throwhand+''''throwfar:''''+inttostr(FatherUse.throwhand(500))+''''m'''';
SonUse.throwhand;
FatherUse.Free;
SonUse.Free;
end;
好了,Delphi的覆盖就聊到这里,嘻嘻,该来杯咖啡享受一下了。下面是Java的覆盖,它可没有那么多关键字。
这是Do.java文件的代码:
class A{ //这是父类
void throwhand(){
System.out.println("right!");
}
}
class SA extends A{ //这是子类
void throwhand(){
System.out.print("left!");
}
}
public class Do{
public static void main(String[] args){
A a=new A(); //父类实例化;
SA s=new SA(); //子类实例化;
System.out.println("-------------------------");
System.out.print("Father throwhand is: ");
a.throwhand(); //调用
System.out.println(" ");
System.out.print("Son throwhand is: ");
s.throwhand(); //调用
}
}
这是效果图:
上一页 [1] [2] [3] 下一页 [Delphi程序]【Gabing Delva 第2篇】 [Delphi程序]【Gabing Delva 第0篇】我的小铁锨(代序)
|