In the following code if I uncomment I3
and implements I2
and I3
then there is a compilation
failure with the following error:
unrelated defaults for m2() from I3 and I2
Which is as fine and expected behavior.
However, when I replace I3
with I
, it compiles successfully and I am getting I2
as output.
public class DefaultMethodTest implements I, I2 {
public static void main(String[] args) {
DefaultMethodTest obj = new DefaultMethodTest();
obj.m2();
}
}
interface I {
default void m2() {
System.out.println("I1");
}
}
interface I2 extends I {
default void m2() {
System.out.println("I2");
}
}
//interface I3 extends I {
//
// default void m2() {
// System.out.println("I3");
// }
//}
Now I have couple of questions here :
Why there is no compilation
failure in second case although both
interface have same default method m2
?
Why I2
got precedence over I
?.
Note: This question is not related to java-8-default-method-inheritance
As per the default method resolution rules, the default method in the most specific default providing interface will be chosen. In your case, both I and I2 has a default method (each) with the same signature. Hence, it will choose I2 which is your most specific default providing interface.
On the other hand, if you implement I2, I3
, there will be conflict that you need to resolve (by implementing m2
in your class).
References:
http://www.lambdafaq.org/how-are-conflicting-method-declarations-resolved/ https://javadevcentral.com/default-method-resolution-rules