How does Java 8 solve Diamond problem of Multiple Inheritance?

In Multiple Inheritance if a class extends more than one classes with two different implementation of same method then it causes Diamond problem.

Consider following example to see problem and solution for Diamond problem in Java 8:

public interface BaseInterface{
default void display() { //code goes here }
}
public interface BaseOne extends BaseInterface { }
public interface BaseTwo extends BaseInterface { }
public class ChildClass implements BaseOne, BaseTwo { }

In the above code, class ChildClass gives compile time error. Java Compiler cannot decide which display method should it invoke in ChildClass.

To solve this problem, Java SE 8 has given the following remedy:

public interface A{
default void display() { //code goes here }
}
public interface B extends A{ }
public interface C extends A{ }
public class D implements B,C{
default void display() {
B.super.display();
}
}

public interface BaseInterface{
default void display() { //code goes here }
}
public interface BaseOne extends BaseInterface { }
public interface BaseTwo extends BaseInterface { }
public class ChildClass implements BaseOne, BaseTwo {
default void display(){
BaseOne.super.display();
}
}

The method invocation at BaseOne.super.display(); solves the Diamond problem as it resolves the confusion for compiler.

Read the full book at www.amazon.com
Posted in Java 8, Java 8 Interview Questions

Leave a Reply

Your email address will not be published. Required fields are marked *

*