The concept of a class makes it possible to define subclasses that share some or all of the main class characteristics. This is called inheritance. Inheritance also allows you to reuse code more efficiently. In a class tree, inheritance is used to design classes vertically. (You can use Interfaces to design classes horizontally within a class tree.) With inheritance, you are defining an "is-a" relationship (i.e. a chow is-a dog). Analysts using UML call this generalization where you generalize specific classes into general parent classes.
Delphi Inheritance
In Delphi, you use the class keyword followed by the parent class in parens. If you leave out the parent class, your class inherits from TObject.
Now let's dive in...
Inheritance versus Interfaces
With inheritance, you design classes that have methods and attributes and then extend those methods and attributes in descendant classes adding functionality as the class hierarchy gets deeper and deeper. In a real sense, you design vertically top to bottom. Interfaces allow you to design horizontally througout your class tree. Interfaces define abstract methods and/or attributes in a psuedo abstract class that if used on a class must be implemented by the class.
Complete Example
More complete example...
//Declare class in Interface section.
TPerson = class(TObject)
private
FName: String;
FAge: Integer;
public
constructor Create;
end;
//Implement class in Implementation section.
constructor TPerson.Create;
begin
inherited; //Call the parent Create method
// Now set a default fruit name
FName := 'unknown';
FAge := 0;
end;
//Use class.
var
Lisa: TPerson;
begin
Lisa := TPerson.Create;
//Defaults.
ShowMessage(Lisa.FName + ' is ' + IntToStr(Lisa.FAge));
//Use class.
Lisa.FName := 'Lisa';
Lisa.FAge := 34;
ShowMessage(Lisa.FName + ' is ' + IntToStr(Lisa.FAge));
end;
Step by Step Example
The following is a step-by-step tutorial on creating your first Delphi class and does include an inheritance example. From this simple tutorial, you can then experiment with the various class inheritance features.
The following are practice certification questions with answers highlighted. These questions were prepared by Mike Prestwood and are intended to stress an important aspect of this KB post. All our practice questions are intended to prepare you generally for passing any certification test as well as prepare you for professional work.