Polymorphism


Polymorphism is somewhat difficult to describe without proper code examples and will be described in more detail later in the book. For now, polymorphism can be described as the ability to access objects of various types through a common ancestor.

For instance, the following procedure can be used to change the Name property of TAnimal type objects.

procedure SetAnimalName(AAnimal: TAnimal; const AName: string); begin   AAnimal.Name := AName; end;

Along with TAnimal type objects, polymorphism enables you to pass TBird or TFish type objects to the SetAnimalName procedure because both classes descend from the common ancestor — the TAnimal class.

Listing 10-6: Polymorphic calls

image from book
program Project1; {$APPTYPE CONSOLE} uses   SysUtils,   Animal in 'Animal.pas'; var   F: TFish;   A: TAnimal;   B: TBird; begin   F := TFish.Create;   A := TAnimal.Create;   B := TBird.Create;   SetAnimalName(F, 'Fish');   SetAnimalName(A, 'Animal');   SetAnimalName(B, 'Bird');   A.Free;   B.Free;   F.Free; end.
image from book

The last thing to note about the SetAnimalName procedure has to do with the AAnimal parameter. The AAnimal parameter is the standard value parameter. Object parameters don't have to be declared as variable in order to change the object's properties. If you declare an object parameter as variable, you'll be passing a pointer to a pointer. That will only slow down the application and unnecessarily complicate your source code.



Inside Delphi 2006
Inside Delphi 2006 (Wordware Delphi Developers Library)
ISBN: 1598220039
EAN: 2147483647
Year: 2004
Pages: 212
Authors: Ivan Hladni

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net