Skip to content

Multiple Inheritance

Multiple inheritance means a single child class inherits from more than one parent class.

Conceptually:

Class C wants to inherit features from both A and B.

For example:

Does Java Support Multiple Inheritance?

Java does NOT support multiple inheritance through classes.

The following is not allowed:

 

☕
filename.java
class A {
    void showA() {
        System.out.println("A");
    }
}

class B {
    void showB() {
        System.out.println("B");
    }
}

class C extends A, B {   // Error
}

Java allows a class to extend only one class.

Why does Java avoid multiple inheritance through classes?

One major reason is the diamond problem.

Suppose:

If both B and C inherit a method from A and D inherits from both B and C, Java would have to decide which inherited implementation D should use.

 

This can create ambiguity.

Multiple Inheritance Using Interfaces

Although Java does not support multiple inheritance using classes, it allows a class to implement multiple interfaces.

☕
filename.java
interface Printable {
    void print();
}

interface Showable {
    void show();
}

class Demo implements Printable, Showable {

    public void print() {
        System.out.println("Printing");
    }

    public void show() {
        System.out.println("Showing");
    }
}

Here:

implements Printable, Showable 

allows Demo to implement both interfaces.

What is an Interface?

An interface is a reference type in Java that defines a contract that implementing classes agree to follow.

Example:

A class implements the interface:

Important Features of Interfaces

An interface can contain:

  • abstract methods
  • constants
  • default methods
  • static methods
  • private methods

For beginners, the most important concept is:

An interface can specify what a class must do, while the implementing class provides how it does it.

Example:

Different classes can implement it differently:

Interface Methods

Traditionally, interface methods are abstract by default.

Example: