Chapter 08 of 26

Types of Inheritance

In Inheritance we connected one child class to one parent. Real hierarchies grow in more interesting ways: one parent may have several children, a chain may be several levels deep, and sometimes a class seems to need two parents. Each of these shapes has a name, and university exams love to ask you to "explain the types of inheritance with diagrams".

In this chapter we'll go through the five classic types (single, multilevel, hierarchical, multiple and hybrid), see which ones Java, C++ and Python support, and understand the diamond problem, which is the real reason Java refuses multiple inheritance of classes.


The Five Types at a Glance

  1. Single         2. Multilevel      3. Hierarchical

     A                  A                    A
     ▲                  ▲                 ▲  ▲  ▲
     |                  |                 |  |  |
     B                  B                 B  C  D
                        ▲
                        |
                        C

  4. Multiple       5. Hybrid (here: hierarchical + multiple = "diamond")

   A     B                 A
    ▲   ▲                ▲   ▲
     \ /                /     \
      C                B       C
                        ▲     ▲
                         \   /
                           D

  (arrows point from child to parent)

Type

Shape

Java classes

Java interfaces

C++

Python

Single

One child, one parent

Yes

Yes

Yes

Yes

Multilevel

Chain: C → B → A

Yes

Yes

Yes

Yes

Hierarchical

Many children, one parent

Yes

Yes

Yes

Yes

Multiple

One child, many parents

No

Yes

Yes

Yes

Hybrid

Mix of two or more types

Only if it needs no multiple class inheritance

Yes

Yes

Yes

Some Indian textbooks also list multipath inheritance: a class reaching the same ancestor along two paths. The diamond above (D → B → A and D → C → A) is exactly that, so multipath is a special case of hybrid inheritance.


1, 2, 3: Single, Multilevel and Hierarchical

Single inheritance: a class has exactly one direct parent.
Multilevel inheritance: a class inherits from a class which itself inherits from another, forming a chain.
Hierarchical inheritance: two or more classes inherit from the same parent.

All three are fully supported in Java, and one small program can show them together:

// Single + multilevel: Animal -> Mammal -> Dog
// Hierarchical: Mammal -> Dog, Mammal -> Cat
class Animal {
    void breathe() { System.out.println(name() + " breathes"); }
    String name() { return getClass().getSimpleName(); }
}

class Mammal extends Animal {               // single inheritance
    void feedMilk() { System.out.println(name() + " feeds milk to its young"); }
}

class Dog extends Mammal {                  // multilevel: Dog -> Mammal -> Animal
    void bark() { System.out.println(name() + " barks"); }
}

class Cat extends Mammal {                  // hierarchical: Dog and Cat share Mammal
    void meow() { System.out.println(name() + " meows"); }
}

public class TypesDemo {
    public static void main(String[] args) {
        Dog d = new Dog();
        d.breathe();     // from Animal (2 levels up)
        d.feedMilk();    // from Mammal
        d.bark();        // its own

        Cat c = new Cat();
        c.breathe();
        c.meow();
    }
}

Output:

Dog breathes
Dog feeds milk to its young
Dog barks
Cat breathes
Cat meows

Two things to notice:

  • In a multilevel chain, a class inherits from all its ancestors, not just its direct parent. Dog can call breathe() from Animal.

  • getClass() returns the actual class of the object, so name(), written once in Animal, prints "Dog" or "Cat". The object knows what it really is.

Hierarchical inheritance is the most common shape in real code: one general class (Shape, Account, Employee) with several specialised children.


4. Multiple Inheritance

Multiple inheritance: a class has two or more direct parents and inherits members from all of them.

It sounds natural. A smartphone is a camera and a music player, so why not class Phone extends Camera, MusicPlayer? Java simply refuses to parse it:

class A { }
class B { }
class C extends A, B { }
MultiErr.java:3: error: '{' expected
class C extends A, B { }
                 ^
1 error

To understand why the Java designers made this choice, we need to look at the diamond problem.


The Diamond Problem

Suppose a photocopier is both a scanner and a printer, and both of those are devices:

              Device
           (int id, start())
             ▲          ▲
             |          |
          Scanner    Printer
     (overrides start) (overrides start)
             ▲          ▲
              \        /
               Copier

Two questions immediately arise:

  1. Duplicate state: Scanner contains a Device part and Printer contains a Device part. Does a Copier have one id or two?

  2. Ambiguous behaviour: if both Scanner and Printer override start(), which one does copier.start() call?

Each language answers these questions differently. Let's see all three.

C++: ambiguity unless you use virtual inheritance

By default C++ gives the copier two separate Device subobjects, so even reading id is ambiguous (g++ errors shown abridged):

#include <iostream>
struct Device { int id = 7; };
struct Scanner : Device { };
struct Printer : Device { };
struct Copier : Scanner, Printer { };
int main() {
    Copier c;
    std::cout << c.id << '\n';
}
diamond_bad.cpp:8:20: error: request for member 'id' is ambiguous
diamond_bad.cpp:2:21: note: candidates are: 'int Device::id'
diamond_bad.cpp:2:21: note:                 'int Device::id'

You could write c.Scanner::id to pick one, but usually you want a single shared Device. That's what virtual inheritance gives you:

#include <iostream>

class Device {
public:
    int id;
    explicit Device(int id) : id(id) { std::cout << "Device(" << id << ")\n"; }
};

class Scanner : virtual public Device {
public:
    Scanner() : Device(1) { std::cout << "Scanner\n"; }
};

class Printer : virtual public Device {
public:
    Printer() : Device(2) { std::cout << "Printer\n"; }
};

class Copier : public Scanner, public Printer {
public:
    // With virtual inheritance the MOST-DERIVED class builds the shared base
    Copier() : Device(99) { std::cout << "Copier\n"; }
};

int main() {
    Copier c;
    std::cout << "id = " << c.id << '\n';             // no ambiguity: one Device
}

Output (g++ 15, -std=c++23):

Device(99)
Scanner
Printer
Copier
id = 99

This output teaches three exam-worthy facts:

  • The shared Device is constructed only once.

  • It is constructed first, by the most-derived class (Copier). The Device(1) and Device(2) calls written in Scanner and Printer are ignored when building a Copier.

  • The other bases are then built in the order they are listed in the class declaration (Scanner then Printer).

Python: the Method Resolution Order (MRO)

Python allows multiple inheritance and solves the ambiguity with a fixed, predictable lookup order computed by the C3 linearization algorithm. Each class appears once in the MRO, so the shared base is never duplicated.

class Device:
    def start(self):
        return "Device.start"


class Scanner(Device):
    def start(self):
        return "Scanner.start -> " + super().start()


class Printer(Device):
    def start(self):
        return "Printer.start -> " + super().start()


class Copier(Scanner, Printer):
    pass


print([cls.__name__ for cls in Copier.__mro__])
print(Copier().start())

Output:

['Copier', 'Scanner', 'Printer', 'Device', 'object']
Scanner.start -> Printer.start -> Device.start

Look closely at the second line: super() inside Scanner did not go to Device. It went to the next class in the MRO, which is Printer. In Python, super() means "next in the MRO of the actual object", not "my parent". This lets each class run exactly once in a cooperative chain.

Java: multiple inheritance of type, not of state

Java's answer is: a class may extend only one class but may implement many interfaces. Interfaces have no instance fields, so problem 1 (duplicate state) can't happen. Problem 2 (duplicate behaviour) can appear since Java 8 introduced default methods, and Java handles it by making it a compile error until you resolve it:

interface Camera {
    default String info() { return "12 MP camera"; }
}

interface MusicPlayer {
    default String info() { return "MP3 player"; }
}

class Phone implements Camera, MusicPlayer { }
DefaultClash.java:9: error: types Camera and MusicPlayer are incompatible;
class Phone implements Camera, MusicPlayer { }
^
  class Phone inherits unrelated defaults for info() from types Camera and MusicPlayer
1 error

The fix is to override the method and, if you want, call a specific parent version with the special InterfaceName.super.method() syntax:

interface Camera {
    default String info() { return "12 MP camera"; }
    void click();
}

interface MusicPlayer {
    default String info() { return "MP3 player"; }
    void play();
}

// A class may implement many interfaces
class Phone implements Camera, MusicPlayer {
    @Override public void click() { System.out.println("Photo taken"); }
    @Override public void play()  { System.out.println("Playing song"); }

    // Required: we must resolve the clash ourselves
    @Override
    public String info() {
        return "Phone with " + Camera.super.info() + " and " + MusicPlayer.super.info();
    }
}

public class DefaultFix {
    public static void main(String[] args) {
        Phone p = new Phone();
        p.click();
        p.play();
        System.out.println(p.info());
    }
}

Output:

Photo taken
Playing song
Phone with 12 MP camera and MP3 player

For completeness, Java's resolution rules for default methods are:

  1. Class wins: a method declared in a class (or inherited from a superclass) beats any interface default.

  2. More specific interface wins: if interface B extends A and both provide the default, B's version is chosen.

  3. Otherwise it's an error: the class must override the method itself, as above.

Interfaces themselves get their own chapter, Abstract Classes vs Interfaces.


Comparing the Three Solutions

Question

C++

Java

Python

Multiple class inheritance?

Yes

No (one extends, many implements)

Yes

Duplicate base state in a diamond?

Yes by default; one shared copy with virtual inheritance

Impossible: interfaces have no instance fields

No: each class appears once in the MRO

Two parents with the same method?

Ambiguity error at the call; qualify with Base:: or override

Compile error; must override, may call X.super.m()

First match in the MRO wins


5. Hybrid Inheritance

Hybrid inheritance is any combination of two or more of the other types in a single hierarchy.

The diamond is the classic example: hierarchical (Device → Scanner, Printer) plus multiple (Copier → Scanner, Printer). In Java you can build a hybrid hierarchy as long as every class has only one superclass, for example:

          Vehicle (class)
          ▲         ▲
          |         |
     Car (class)  Truck (class)         ← hierarchical
          ▲
          |
   ElectricCar (class) ──implements──▶ Chargeable (interface)
                                        ← "multiple" via interface

So the honest statement for interviews is: Java supports hybrid inheritance only through interfaces wherever the hybrid needs more than one parent.


Common Mistakes

  • Saying "Java doesn't support multiple inheritance" without qualification. Java doesn't support multiple inheritance of classes (state and implementation), but it does support multiple inheritance of type through interfaces, and partial multiple inheritance of behaviour through default methods.

  • Confusing multilevel with multiple. Multilevel is a chain (each class has one parent); multiple is one class with several parents.

  • Assuming super() in Python means "my parent". It means "next class in the MRO", which may be a sibling class.

  • Forgetting that with C++ virtual inheritance the most-derived class constructs the virtual base. Arguments passed by intermediate classes are ignored.

  • Using multiple inheritance to combine unrelated features. Even where a language allows it, composition (giving a Phone a Camera field) is often the cleaner design.


Interview and GATE-Style Questions

Why doesn't Java support multiple inheritance of classes?

To avoid the diamond problem: with two parent classes, a child could get two copies of a common ancestor's fields and two conflicting method implementations. The Java designers chose simplicity: one superclass, but any number of interfaces, which carry no instance state.

How does Java resolve two interfaces providing the same default method?

If a superclass provides the method, it wins. If one interface is more specific (extends the other), it wins. Otherwise the class fails to compile and must override the method; inside the override it can call InterfaceName.super.method().

What is virtual inheritance in C++?

Declaring a base as virtual (class B : virtual public A) makes all paths in a diamond share a single subobject of A. The most-derived class is responsible for constructing that shared base, and it is constructed before all non-virtual bases.

Difference between multilevel and multiple inheritance?

Multilevel: a chain A ← B ← C where each class has one direct parent. Multiple: one class has two or more direct parents, e.g. C ← A and C ← B.

Python: class D(B, C), where B and C both extend A. What is D.__mro__?

D, B, C, A, object. Each class appears once, children before parents, and the order of bases in the class statement (B before C) is preserved.

Is hybrid inheritance possible in Java?

Yes, as long as no class needs more than one superclass. Where the hybrid involves multiple parents, those extra parents must be interfaces.


Summary

  • Five classic types: single, multilevel (chain), hierarchical (one parent, many children), multiple (one child, many parents), hybrid (a mix). Multipath is a diamond-shaped hybrid.

  • The diamond problem = duplicate ancestor state + ambiguous inherited methods.

  • C++ allows multiple inheritance; use virtual inheritance to share one copy of the common base.

  • Python allows it and uses the C3 MRO; super() follows the MRO.

  • Java allows one superclass and many interfaces; clashing default methods must be overridden explicitly.

All this inheritance pays off when one piece of code can work with many kinds of objects. That ability is Polymorphism, the fourth pillar and the subject of the next chapter.