Learn Java with Projects by Dr. Seán Kennedy and 
Maaike van Putten

Learn Java with Projects by Dr. Seán Kennedy and 
Maaike van Putten

Author:Dr. Seán Kennedy and 
Maaike van Putten
Language: eng
Format: epub
Publisher: Packt Publishing Pvt. Ltd.
Published: 2023-11-27T00:00:00+00:00


Multiple interface inheritance

The Diamond of Death (https://en.wikipedia.org/wiki/Multiple_inheritance#:~:text=The%20”diamond%20problem”%20(sometimes,from%20both%20B%20and%20C) arises when a class finds that it has inherited two methods of the same name; which one should it work with? This was a concern in C++, where multiple-class inheritance is allowed and was an influencing factor in prohibiting multiple-class inheritance in Java.

However, Java has always allowed a class to implement multiple interfaces. However, now that Java 8 allows default methods, which have code bodies that are inheritable, is it not possible for Java 8 to encounter a “Diamond of Death” scenario? Couldn’t a class implement two (or more) interfaces that have the same default methods? What happens then? The good news is that the compiler steps in and forces your class to override the “offending” default method.

So, that just leaves the question, what if we wanted to access each of the default methods? For example, let’s assume we have a default method called foo() in interface A and a default method called foo() in interface B. What if, in our class, we wanted to execute the three different versions of foo() – the one from A, the one from B, and the one from our class that the compiler forced us to create?

Figure 10.7 shows how to do this in code:



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.