Suppose I have the following code:
interface HumanoidForm {
default HumanoidForm reproduce() {
<appropriate code for humanoid form reproduction>
}
}
class Android extends Machine implements HumanoidForm {
public HumanoidForm reproduce() {
<appropriate code for android reproduction> // how to use HumanoidForm's default implementation here?
}
}
Now suppose "appropriate code for android reproduction" is best described by using "appropriate code for humanoid form reproduction" as a sub-routine. How can I access "appropriate code for humanoid form" from within "appropriate code for android reproduction"? I can think of three ways, but none of them works:
- Simply invoking reproduce() invokes the overriding implementation.
- Writing ((HumanoidForm) this).reproduce() still invokes the overriding implementation.
- Mimicking the re-use of implementations of methods in super classes by overriding methods, one may think of writing super.reproduce(). However, that refers to Machine's implementation of reproduce, which may not even exist.
So it seems there is no way to re-use the code in the default method for overriding. Is that really so?
Take a look at this: https://blog.idrsolutions.com/2015/01/java-8-default-methods-explained-5-minutes/
In particular the section where it says "If we want to specifically invoke one of the sayHi() methods in either InterfaceA or InterfaceB, we can also do as follows:"
No, you can reuse the code. You can easily test it and you will see that the following code works:
OUTPUT:
Actually, you can choose freely the existing implementation. Let me give you a scenario slightly more complicated than yours. To make things worse, all
A
,B
&C
has the same method signature.Now, I create a subclass to C which implements A & B:
The output will be:
when you run: