How multiple inheritance in Java is achieved?

Multiple inheritance in Java programming is achieved or implemented using interfaces. Java does not support multiple inheritance using classes.
In simple term, a class can inherit only one class and multiple interfaces in a java programs. In java terminology, we can say that

“A class can extend only one class but it can implement multiple interfaces.”

For example, below inheritance using multiple classes is wrong as two classes cannot be extended or inherited. Class C is inheriting class A and B.

class A{}
class B{}
class C extends A,B{}

Below program example for multiple inheritance in java language is correct as this example is extending only one class A and implementing multiple interfaces i.e. IB and IC.

class A{}
interface IB{}
interface IC{}

class D extends A implements IB, IC{
	
}

NOTE: Whenever the question “what is multiple inheritance in java” is asked in an interview, most of the candidates says java does not support multiple inheritance and that’s it. This answer is partially correct and is not a satisfactory answer and we need to state explicitly that java supports multiple inheritance using interfaces not classes.

Here is a complete program example and description for how multiple inheritance is achieved in java using interfaces.

You can read a nice notes on interface in java programming with various examples.

Example of Multiple Inheritance in Java

Here is the complete java program example of multiple inheritance using interfaces. Also, it will extend one class as extending one class in java is allowed.

In this java program, Bird class will extend one class (Color) and use multiple inheritance properties by implementing 2 interfaces i.e. IFlyable and IEatable

class Color{
	public void red(){
	
		System.out.println("Color Red");
	}
}

interface IFlyable
{
     void fly();
}
interface IEatable
{
    void eat();
}

//Bird class will implement interfaces and extend Color class
class Bird extends Color implements IFlyable,IEatable
{
    //Implement method of interfaces
    public void fly(){
    	System.out.println("Bird flying");
    }
    public void eat()
    {
    	System.out.println("Bird eats");
    }
    //It can have more own methods.
}

public class Program {

	public static void main(String[] args) {

        Bird b = new Bird();
        //Interface implemented methods by Bird class
        b.eat();
        b.fly();
        //Color extended method by Bird class
        b.red();
	}

}

Output:
Bird eats
Bird flying
Color Red

CONCLUSION:

  • Multiple inheritance in java programming is achieved using only interfaces not classes.
  • Java does not support multiple inheritance using classes like C++ language. This is eliminated by design.

Related Posts