I notice that there are many students and developers out there who have not properly understood how inheritance is to be applied in programs. They sometimes create a mess because of improper designing of class relationships, armed with their syntactic knowledge of inheritance! Any programmer can derive class B from class A, but only a professional will know whether to inherit or not!Let me start with the definition of inheritance: It is the mechanism by which one class derives all features of another class. The word that I want to emphasize here is “all”, and I want to contrast it with phrases that others often use to justify inheritance, like “some features”, “many features”, “most features” and “almost all features”. If you are trying to achieve a semantic relationship between two classes using inheritance, do not inherit unless you want all features to be derived.
Somehow, one of the most common examples of inheritance I hear from people is “Parent-Child”. I call this the classical bad example of inheritance! Classical because it is the most common example I hear, and bad for the simple reason that the child does not inherit all features from it’s parent. And no, “many”, “most” or “almost all” won’t do!
A simple test to figure out whether you are wrong in inheriting is the “is-a” relationship test. Given classes A and B, if the phrase “B is a A” either does not make sense or is not completely true at all times, you should not attempt to inherit class B from class A. Applying this to the “Parent-Child” example, the statement “Child is a Parent” is absurd! This is sufficient for us to conclude that inheritance in this case is a bad idea.
If your decision to inherit a class B from class A was semantically correct, then the Liskov substitution principle will hold good, which I can simplify and rephrase to a general statement that I call The Law of Substitutability: “Derived class entities are perfectly substitutable for base class entities”. Thus, if you decide to derive class Dog from class Animal, because Dog has all properties of Animal, then in any place where an animal is required, a dog can be substituted!
This general statement has 3 specific forms:
- Derived class objects are perfectly substitutable for base class objects
- Derived class pointers are perfectly substitutable for base class pointers
- Derived class references are perfectly substitutable for base class references
In a separate article later on, I’ll throw more light on each of these 3, and also show why we do not practically use the first form.
Related Articles
No user responded in this post