In fact, there is an "is" operator that checks whether an Object is an instance of a class or its ancestors. This is called "dynamic type checking" and is advanced. Check help for details.
Depending on your needs, “virtual methods” may be what you need, as others explain. Please check out the link posted about "virtual methods" as the correct OOP method.
In the example below
if AFruit is TApple then
and
if AFruit is TFruit then
both return true
type
TFruit = class
protected
FName: string;
public
property Name: string read FName;
end;
TApple = class(TFruit)
public
constructor Create;
end;
TPear = class(TFruit)
public
constructor Create;
end;
TForm1 = class(TForm)
Button1: TButton;
mixed: TLabel;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
FMixValue: string;
procedure MixFruits(AFruit: TFruit);
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
APear: TPear;
AApple : TApple;
begin
APear := TPear.Create;
AApple := TApple.Create;
MixFruits(APear);
MixFruits(AApple);
mixed.Caption := FMixValue;
end;
{ TPear }
constructor TPear.Create;
begin
inherited;
FName := 'Pear';
end;
{ TApple }
constructor TApple.Create;
begin
inherited;
FName := 'Apple';
end;
procedure TForm1.MixFruits(AFruit: TFruit);
begin
FMixValue := FMixValue + ' ' + AFruit.Name;
if AFruit is TApple then
ShowMessage('An Apple')
else if AFruit is TPear then
ShowMessage('A Pear')
else
ShowMessage('What is it?');
end;
source
share