我的顶级课程是TBaseDB
,它有一个后代TCommonDB
(, and TCommonDB
将有多个后代,例如TProdDB
and TDevDB
).
让我们创建一个函数each类定义,称为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
or TCommonDB
, and
- the proper
Test
过程将根据实例被调用TBaseDB
or TCommonDB
?
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
in TApple.ShowMessage
and TOrange.ShowMessage
意思是?他们需要处于程序的顶端吗?如果忽略它们会发生什么?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)