fellow99说: delphi的接口的意义是不是跟c++和java的不同呢?
iinterface1 = interface
end;
iinterface2 = interface(iinterface1)
procedure method();
end;
tclass1 = class(tinterfacedobject, iinterface2)
......
end;
首先,编译器不承认tclass1是iinterface1的派生,一定要写成tclass1 = class(tinterfacedobject, iinterface2, iinterface1)才可以。
接着,这样子也不行:
function xxx(): iinterface2;
var
obj: tobject;
begin
obj := tclass1.create;
result := obj as iinterface2; //不行
result := iinterface2(obj); //也不行
end;
想想没有道理, kbs说在d7中是可以的,我决定在d5中试一试。
试验的结果是,在d5中第一个问题是不存在的,第二个问题的,改 obj 的声明为:
var
obj: tclass1;
就可以了。因为tobject 是不能 as 为 iinterface2 的,因为它的定义中并没有从 iinterface2 继承。
据我看来,接口的意义不仅体现在语法上,更多的是应用方式:声明功能而不是实现,可以有各种不同的实现。应用的场合是有预想到的多个实现。如 ado、dbexpress、jdbc 的驱动程序,由于数据库类别的不同,将有不同的实现。