I have the code below. IAnimal is the base interface of all animal on my application.
Why I can't declare var with the the type I want, get a object that implement the base interface IAnimal and call the method ?
type
IAnimal = interface
end;
ICat = interface(IAnimal)
procedure Hunt;
end;
IBird = interface(IAnimal)
procedure Fly;
end;
TCat = class(TInterfacedObject, ICat)
procedure Hunt;
end;
TBird = class(TInterfacedObject, IBird)
procedure Fly;
end;
TAnimalType = (atCat, atBird);
TAnimalFactory = class
class function GetAnimal(aType: TAnimalType): IAnimal;
end;
procedure TCat.Hunt;
begin
Writeln('I hunt');
end;
procedure TBird.Fly;
begin
Writeln('I fly');
end;
class function TAnimalFactory.GetAnimal(aType: TAnimalType): IAnimal;
begin
case aType of
atCat: Result := TCat.Create;
atBird: Result := TBird.Create;
end;
end;
var
i: ICat;
begin
i := TAnimalFactory.GetAnimal(atCat);
// [dcc32 Error] Project1.dpr(63): E2010 Incompatible types: 'ICat' and 'IAnimal'
i.Hunt;
end.