Java8 Diamond Problem – Solving Java Way

With the introduction of default method in Java 8, concrete methods gets a green flag to be written inside interfaces. Being a seasoned programmer you can easily guess what trouble this might lead to: the diamond problem.

There could be two use cases:

i.  A class implements more than one interfaces having the same default method signature.

See the following example (written in Java SE 8) where compiler raises alarm about compilation failure –

class SmartPhone is implementing two the interfaces, both having the same default method signature – the code for SmartPhone will not compile and will give out this error during compilation:

You may also like  Embracing Java 9 ~ Overview [Part -1]

To resolve this, you have to do either of this:

a)  implement connectoToInternet() method locally
b)  declare connectToInternet() method as public and abstruct so that there will be a concrete implementation later by the implementer (of course, you need to declare the enclosing class as abstract too)

After you resolve the compilation error, you can still access the parent’s copy of method as follows:

MobilePhoneWithInternet.super.connectToInternet();
MobilePhoneWithHighSpeedInternet.super.connectToInternet();

ii. A class extends one class and implements one or more interfaces with the same non-abstract method signature.

You may also like  Embracing Java 9 ~ Working With JShell

The compiler doesn’t complain as “class wins over interface”. By this rule, if a base class and a base interface define methods with the same signature, the method definition in the base class is used and the interface definition is ignored.

 

 

Thanks for reading.
Have any questions in mind ? Put in comments and I will get back with explanation.

Best Regards,
BanerjeeBabu

 

Leave a Reply

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