我的顶级课程为TBaseDB
,其后代TCommonDB
(和TCommonDB
将有多个后代,例如TProdDB
和TDevDB
)。
让我们在每个类定义中创建一个名为Test1
的函数。现在,它所做的只是ShowMessage('Some literal')
只是为了向我展示正在执行的代码。
直到运行时我才知道类类型。我希望有共同的代码,但行为不同。
我想要的是这样的:
var
MyObj: TBaseDB;
begin
//pseudo-code...
if RadioButton1.Checked then
MyObj := TBaseDB.Create
else
MyObj := TCommonDB.create;
MyObj.Test1;
end;
我似乎无法让它工作,我想它是在我的班级定义中。应如何定义Test1
以便:
TBaseDB
,TBaseDB
或TCommonDB
,也可以是Test
或TBaseDB
TCommonDB
程序
醇>
答案 0 :(得分:10)
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
?inherited
和TApple.ShowMessage
中的TOrange.ShowMessage
是什么意思?他们是否需要处于程序的首位?如果省略它们会发生什么?