Multiple inheritance in java is the capability of creating a single class with multiple superclasses. Unlike some other popular object oriented programming languages like C++, java doesn’t provide support for multiple inheritance in classes.Java doesn’t support multiple inheritance in classes because it can lead to diamond problem and rather than providing some complex way to solve it, there are better ways through which we can achieve the same result as multiple inheritance

Diamond Problem in Java

To understand diamond problem easily, let’s assume that multiple inheritance was supported in java. In that case, we could have a class hierarchy like below image.

diamond problem in java

Let’s say SuperClass is an abstract class declaring some method and ClassA, ClassB are concrete classes.

SuperClass.java

package com.journaldev.inheritance;

public abstract class SuperClass {

	public abstract void doSomething();
}

ClassA.java

package com.journaldev.inheritance;

public class ClassA extends SuperClass{
	
	@Override
	public void doSomething(){
		System.out.println("doSomething implementation of A");
	}
	
	//ClassA own method
	public void methodA(){
		
	}
}

ClassB.java

package com.journaldev.inheritance;

public class ClassB extends SuperClass{

	@Override
	public void doSomething(){
		System.out.println("doSomething implementation of B");
	}
	
	//ClassB specific method
	public void methodB(){
		
	}
}

Now let’s say ClassC implementation is something like below and it’s extending both ClassA and ClassB.

ClassC.java

package com.journaldev.inheritance;

public class ClassC extends ClassA, ClassB{

	public void test(){
		//calling super class method
		doSomething();
	}

}

Notice that test() method is making a call to superclass doSomething() method. This leads to the ambiguity as compiler doesn’t know which superclass method to execute. Because of the diamond shaped class diagram, it’s referred as Diamond Problem in java. Diamond problem in java is the main reason java doesn’t support multiple inheritance in classes.

Notice that the above problem with multiple class inheritance can also come with only three classes where all of them has at least one common method.

asked in Java 10 by (560 points)

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.

Java Interview Questions and Answers 2018

>
...