Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Multiple Inheritance?

Imagine that you are creating a game that simulates the world in a fairly realistic way. The simulation includes various species of animal, some of which can fly. You might be tempted to represent with different animal species in a class hierarchy like this:

---
config:
  class:
    hideEmptyMembersBox: true
---
classDiagram
  Animal <|-- FlyingAnimal
  FlyingAnimal <|-- Bird
  FlyingAnimal <|-- Insect
  Bird <|-- Eagle
  Insect <|-- Wasp

The problem with this hierarchy is that it assumes that all birds and insects fly, which is not the case. So how do we express the idea that an eagle is a bird and that it can fly?

One solution might be to have a hierarchy like this:

---
config:
  class:
    hideEmptyMembersBox: true
---
classDiagram
  Animal <|-- Bird
  Animal <|-- Insect
  Bird <|-- Eagle
  Flyer <|-- Eagle
  Flyer <|-- Wasp
  Insect<|-- Wasp

Here, Eagle is a kind of Bird and a kind of Flyer. It has two superclasses. This is termed multiple inheritance.

Multiple inheritance is allowed in some object-oriented languages, but not in others. For example, it is possible in C++ and Python, but not in C# or Java, and not in Kotlin.

To understand why, consider the classic ‘inheritance diamond’ scenario:

classDiagram
  direction LR
  A <|-- B
  A <|-- C
  B <|-- D
  C <|-- D
  class A {
    x: String
    y: Int
  }

Here, class A has properties x and y. Class B inherits from A, thereby inheriting both of those properties. Class C does the same.

So what happens when we have a class D, inheriting from both B and C? Does D get two properties named x and two named y? If so, which of them will be used we attempt to access x or y in an instance of D?

By not supporting multiple inheritance, C#, Java and Kotlin avoid having to deal with problems like this. Yet these languages are still able to exploit some of the benefits of multiple inheritance, through the use of interfaces.