Inheritance


Classes, like animals and plants in the real world, have the ability to inherit the properties and methods of their parents. Not only do classes have the ability to inherit the functionality of a parent class, they always do so. If you fail to specify the parent class in the class declaration, Delphi implicitly derives your class from the ultimate parent — the TObject class. To explicitly define a parent class, you have to specify the class name after the reserved word:

TNewClass = class(TParentClass)

For instance, the TAnimal class used earlier implicitly derives from the TObject class. If you want, you can also explicitly define the parent class of the TAnimal class:

type   TAnimal = class(TObject)     Name: string;     Age: Integer;     Hungry: Boolean;   end;.

The only reason we are able to instantiate objects of type TAnimal is because the TAnimal class inherits the necessary methods from the TObject class. The TObject class encapsulates the essential methods necessary to create and destroy objects like Create, Destroy, and Free.

To view the entire list of methods inherited from the TObject (or any other parent class), you can utilize the Code Insight feature of the Code Editor (see Figure 10-1). To display the list of properties and methods that belong to an object, write the object name followed by a period and press Ctrl+Space.

image from book
Figure 10-1: Methods inherited from the TObject class

The TAnimal class can also be used as a parent class for other classes. For instance, the TAnimal class can be the parent class of TBird or TFish classes.

type   TAnimal = class     Name: string;     Age: Integer;     Hungry: Boolean;     procedure ShowInfo;   end;   TFish = class(TAnimal)     Carnivorous: Boolean;     Length: Integer;   end;   TBird = class(TAnimal)     CanFly: Boolean;   end;

Both TFish and TBird classes inherit the functionality of the TAnimal class but also enhance the original class by introducing new properties like Length and CanFly:

var   F: TFish; begin   F := TFish.Create;   F.Name := 'Rainbow Trout';   F.Length := 54;   F.ShowInfo;   F.Free; end.



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

Similar book on Amazon

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