“Is a” versus “Has a”

Reading Time: < 1 minute

Don’t confuse inheritance with nesting (having a member that refers to another object).
Declaring an object as a data field inside a class just sets up a reference variable to the object with
no special privileges or relationship. In contrast, inheritance says the subclass is a variation of the
superclass that extends its semantics in some way.
The way to distinguish between these two cases is to ask yourself the “is a” versus “has a”
question. Let’s assume you have a “car” class and an “engine” class, and you want to decide
whether to use inheritance or nesting to associate the two. Would you say “a car has an engine” or
“a car is an engine?” If the answer is “has a,” use nesting. If the answer is “is a,” use inheritance.
Similarly, if we have a “mammal” class and a “dog” class, we know that a “dog is a mammal.” We
would use inheritance to add the canine specializations to the mammal class resulting in the dog
class.
The rule of thumb is that inheritance is for specialization of a type or changing its behavior.
Container classes are for data structure reuse.