我的顶级类是 TBaseDB
,它有一个后代 TCommonDB
(并且 TCommonDB
将有多个后代,例如 TProdDB
和 TDevDB
)。
让我们在每个类定义中创建一个名为Test1
的函数。目前,它所做的只是一个 ShowMessage('Someliteral')
只是为了向我显示正在执行的代码。
直到运行时我才知道类类型。我想要有共同的代码,但有不同的行为。
我想要的是这样的:
var
MyObj: TBaseDB;
begin
//pseudo-code...
if RadioButton1.Checked then
MyObj := TBaseDB.Create
else
MyObj := TCommonDB.create;
MyObj.Test1;
end;
我似乎无法让它工作,我想它在我的类定义中。应如何定义 Test1
以便:
- 我可以将变量声明为
TBaseDB
, - 创建的类可以是
TBaseDB
或TCommonDB
,并且 - 将根据实例是
TBaseDB
还是TCommonDB
来调用正确的Test
过程?<
最佳答案
program Project1;
{$APPTYPE CONSOLE}
uses
SysUtils;
type
TFruit = class
public
procedure ShowMessage; virtual; abstract;
end;
TApple = class(TFruit)
public
procedure ShowMessage; override;
end;
TOrange = class(TFruit)
public
procedure ShowMessage; override;
end;
{ TApple }
procedure TApple.ShowMessage;
begin
Writeln('I''m an apple!');
end;
{ TOrange }
procedure TOrange.ShowMessage;
begin
Writeln('I''m an orange!');
end;
var
fruit: TFruit;
begin
fruit := TApple.Create;
fruit.ShowMessage;
Writeln('Press Enter to continue.');
Readln;
end.
关键字abstract
允许您在基类中根本没有实现。不过,您也可以在那里实现:
program Project2;
{$APPTYPE CONSOLE}
uses
SysUtils;
type
TFruit = class
public
procedure ShowMessage; virtual;
end;
TApple = class(TFruit)
public
procedure ShowMessage; override;
end;
TOrange = class(TFruit)
public
procedure ShowMessage; override;
end;
{ TFruit }
procedure TFruit.ShowMessage;
begin
Writeln('I''m a fruit.');
end;
{ TApple }
procedure TApple.ShowMessage;
begin
inherited;
Writeln('I''m an apple!');
end;
{ TOrange }
procedure TOrange.ShowMessage;
begin
inherited;
Writeln('I''m an orange!');
end;
var
fruit: TFruit;
begin
fruit := TApple.Create;
fruit.ShowMessage;
Writeln('Press Enter to continue.');
Readln;
end.
练习:
- 在每种情况下,如果您创建
TFruit
实例,会发生什么? - 在第二种情况下,
TApple.ShowMessage
和TOrange.ShowMessage
中的inherited
是什么意思?他们需要处于程序的顶端吗?如果省略它们会发生什么?
关于delphi - 当我调用基类上的方法时,如何调用后代的实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15114690/