Skip to content

Inheritance. A first insight

Inheritance1-GUI
Inheritance 1 - GUI

The principle of inheritance involves the encapsulation mechanism too; so that we must pay attention to its usage.

In facts when we design a class and decide which items must be public or not, we bind them to precise ranges of action.

But now we add another degree in decision, because of the hypothetical necessity to design a class which at least to derive another one from.
This means that the inheriting classes receive all the parent's features exactly as they're written: private stuff to private, public stuff to public.

A last choice exists, under the protected zone (see in any class code we publish); but we'll see it next time.

But... why to inherit a class?

Certainly not to have just a copy, because it would be useless.

Surely to specialize the original class, called father, into a new one, called child.

A common example is the human being, which can become man and woman, for example.

In our case we have the usual Employee class, to be adapted in few things where needed by the context.
Here we specialize the employee into a worker, so that the Worker class inherits from the Employee:

uses
  Classes,SysUtils,Dialogs,
  Employee; // Worker IS an employee

This is the translation in freepascal code of the inheritance!
You now understand that the uses is not a simple directive to make a file get access to another one (which would be in case of procedural approach), but a directive to make every class of this last inheritable.
If Worker uses Employee then the first inherits from the second.

Now its just a matter of differentiation from the father, which is possible by defining and declaring other new members that don't belong to the parent class.
An employee is generic, why worker has more informations to manage, like the working hours for example; that's why we surely have to add a member to save the amount of hours, and methods to set/get it too.

A little digression: you can now better appreciate the powerful of a TList object, that it's originally an array of generic pointers.
We know that every object added to it performs a casting, so the generic pointer becomes a pointer to the new object.
Here we'll do the same for the employee objects, and for the workers too!
Beautiful: this gives us a way to manage them all just from the Main unit, who hosts the Form class.

It's worthwhile to notice this aspect, for an important reason we're going to discuss.