Multiple Inheritance in Java

In multiple inheritance a single class extends from more than one class. But Java does not support multiple inheritance among classes. Multiple inheritance in Java is possible with Interface. Let us understand with help of diagram about multiple inheritance :

Class A is inheriting from class B and class C at the same time.

Why Java does not support Multiple Inheritance among classes ?

Consider the below code to understand the problem:

public class Tech4Humans {
	public static void main(String[] args) {
		A1 obj = new A1();
		//Ambiguity will arise. Because complier will not be able to decide newFunc() of class B1 has to be executed or class C1 
		obj.newFunc();
	}	
}

class B1{
	int var2;
	
	void newFunc() {
		System.out.println("method in class B1");
	}
}

class C1{
	int var3;
	
	void newFunc() {
		System.out.println("method in class C1");
	}
}

//Compiler will throw an error since Java does not support Multiple inheritance
class A1 extends B1,C1{
	int var1;
	
	void methodA() {
		System.out.println("method in class A1");
	}
}

Output

Compilation Error

In the above code class A1 is trying to inherit from both class B1 and class C1. In both class B1 and class C1, a method is defined with same name – newFunc(). So when the object of class A1 tries to access newFunc() then there will be be ambiguity about which class’ function to access.

So to avoid this ambiguity Java does not support Multiple inheritance among classes.

Interface Support for Multiple inheritance in Java

Java support the concept of multiple inheritance through Interface. In interface we only declare the function while the implementation of the function is given by the class implementing the function, due to which the ambiguity seen in the previous section will never arise.

Let us understand this with an example :

public class Tech4Humans {
	public static void main(String[] args) {
		A obj = new A();
		//No ambiguity here since class A object will call the newFunc() implementation in class A
		obj.newFunc();
	}

}

interface B{
	int var2=10;
	
	void newFunc();
}

interface C{
	int var3=20;
	
	void newFunc();
}

//Compiler will not throw an error since Java support Multiple inheritance for interface
class A implements B,C{
	int var1;
	
	void methodA() {
		System.out.println("method in class A");
	}

	@Override
	public void newFunc() {
		System.out.println("newFunc implementation in class A");
		
	}
}

Output

newFunc implementation in class A

In the above code we have made 2 interfaces B and C. They have a common function declared with the name newFunc(). Class A is implementing both the interfaces and also provide the implementation of newFunc(). So when the object of class A calls newFunc() there will be no ambiguity since it will call the method implemented by class A.

Hence, Java supports multiple inheritance for interfaces.

Leave a Comment