Java 8 diamond problem

Java 8 introduced default and static method in JDK 8, it is  possible to define non-abstract methods in interfaces. If java  one class can implement multiple interfaces and because there can be concrete methods in interfaces, the diamond problem has surfaced again. What will happen if two interfaces have methods  the same name and a Java class inherit both.

Diamond problem with examples:

As shown in below code, we have two interface with same default method name and Demo class implementing the both interface and both interface have same name of default method means through the ambiguity issue and this code will not compile in Java 8.

interface interface1{
    default void hello(){
        System.out.println("Hello interface 1");
    }
}

interface interface2{
    default void hello(){
        System.out.println("Hello interface 2");
    }
}

public class Java8Diamond implements interface1,interface2{
    public static void main(String[] args) {
          Java8Diamond java8Diamond=new Java8Diamond();
          java8Diamond.hello();
    }
}

java8.Java8Diamond inherits unrelated defaults for hello() 
from types java8.interface1 and java8.interface2

Now, the problem is not that we have implemented two interfaces with default methods of the same name. The Actual problems come when we created an object of a Java8Diamon class and called the hello() method.

At this point in time, the compiler doesn't know that which hello() method should call because of ambiguity and that results in the compiler error you have seen above.


How to avoid Diamond Problem With Default Methods in Java 8

To solve this problem we need to override the same hello() method in  implement class.

public class Java8Diamond implements interface1,interface2{
    @Override
    default void hello(){
        System.out.println("Hello java8diamond ");
    }
    public static void main(String[] args) {
          Java8Diamond java8Diamond=new Java8Diamond();
          java8Diamond.hello();
    }
}

In above code we have override the hello() method in implemented class to resolve the diamond problem.



No comments:

Post a Comment