Inheritance Hierarchy

Learn about inheritance hierarchy in this lesson.

Inheritance: An "is a” relationship

We have seen that implementation inheritance is about acquiring members. Consider this kind of inheritance only if the subtype can be thought of as a kind of the supertype, like in the phrase “alarm clock is a clock.”

“Is a” is not the only relationship between types; a more common relationship is the “has a” relationship. For example, let’s assume that we want to add the concept of a Battery to the Clock class. It would not be appropriate to add Battery to Clock by inheritance because the statement “clock is a battery” is not true:

class Clock : Battery {    // ← WRONG DESIGN
    // ...
}

A clock is not a battery; it has a battery. When there is such a relationship of containment, the type that is contained must be defined as a member of the type that contains it:

class Clock {
    Battery battery;       // ← Correct design
// ...
}

Inheritance from a single class

Classes can only inherit from a single base class (which itself can potentially inherit from another single class). In other words, multiple inheritance is not supported in D.

For example, assuming that there is also a SoundEmitter class, it is not possible to inherit AlarmClock both from Clock and SoundEmitter and even though “alarm clock is a sound emitting object” is also true:

class SoundEmitter {
    // ...
}
class AlarmClock : Clock, SoundEmitter { // ← compilation ERROR
    // ...
}

On the other hand, there is no limit to the number of interfaces that a class can inherit from. You will see the interface keyword in a later chapter.

Additionally, there is no limit to how deep the inheritance hierarchy can go:

class MusicalInstrument {
    // ...
}
class StringInstrument : MusicalInstrument {
    // ...
}
class Violin : StringInstrument {
    // ...
}

The inheritance hierarchy above defines a relationship from the more general to the more specific: musical instrument, string instrument, and violin.

Hierarchy charts

Types that are related by the “is a” relationship form a class hierarchy.

According to OOP conventions, class hierarchies are represented by superclasses being on the top and the subclasses being at the bottom. The inheritance relationships are indicated by arrows pointing from the subclasses to the superclasses.

For example, the following can be a hierarchy of musical instruments:

Get hands-on with 1200+ tech skills courses.