Java Reference
In-Depth Information
Rule 2 doesn't help you now because there's no more-specific interface to select. Both hello
methods from A and B could be valid options. Thus, the Java compiler will produce a compile
error because it doesn't know which method is more suitable: “Error: class C inherits unrelated
defaults for hello() from types B and A.”
Resolving the conflict
There aren't many solutions to resolve the conflict between the two possible valid methods; you
have to explicitly decide which method declaration you want C to use. To do this, you can
override the hello method in class C and then in its body explicitly call the method you wish to
use. Java 8 introduces the new syntax X.super.m(...) where X is the superinterface whose
method m you want to call. For example, if you want C to use the default method from B, it looks
like this:
Have a go at Quiz 9.3 to investigate another related tricky case.
Quiz 9.3: Almost the same signature
For this quiz, assume interfaces A and B are declared as follows:
public interface A{
default Number getNumber(){
return 10;
}
}
public interface B{
default Integer getNumber(){
return 42;
}
}
And class C is declared as follows:
Search WWH ::




Custom Search