Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)

Before Java 7, we have classes to abstract method implementation and interfaces to abstract object structure. But, from java 8 we can implement methods in interfaces using default methods that would give rise to the diamond issue. For example,

interface A

 { 

public void execute(); 

}

 interface B extends A

 {

 default void execute()

 { 

System.out.println("B called");

 }

 }

 interface C extends A 

{

 default void execute()

 { System.out.println("C called");

 }

 } 

class D implements B, C 

{ }

In the above example, if the method new D.execute() is implemented what would happen? And how can you avoid it?

1 Answer

0 votes
by (13.1k points)

In the above example, the classes already have multiple definitions for the method execute() the compiler will not know what method to run and the program will not compile.

To avoid that you need to call execute() from D in such a way that the compiler knows which execute() to run. You can do something like this:

class D implements B, C

{

@override

default void execute(){

B.super.execute();

C.super.execute();

}

}

This would run the program and makes it clearer to the compiler.

Want to learn Java? Check out the Java course from Intellipaat.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Feb 20, 2021 in Java by Jake (7k points)
0 votes
1 answer
asked Feb 18, 2021 in Java by Jake (7k points)
0 votes
1 answer
asked Feb 16, 2021 in Java by Jake (7k points)

Browse Categories

...