I have stumbled upon a strange issue working with default methods.
Consider this situation:
interface A {
int method();
}
interface B {
default int method() {
return 1;
}
}
class C implements A, B {
void anotherMethod() { }
}
I would expect class C
to be fine as-is: it should implement method
, because that's the contract of both A
and B
, and it actually does, because B
provides a default implementation.
However, the compiler does not agree with me, saying:
C is not abstract and does not override abstract method method()
I can totally see the issue in other similar cases, such as this one, but I can't figure out what's wrong with this code.
CodePudding user response:
There may be nothing wrong from a syntax perspective, but the question is: does it make sense to have a default method from interface B, override the abstract method of another unrelated interface A?
Imagine the two interfaces represented two different ways to compute a value: one that allows null
values to be returned, and the other does not. If the default method for the first interface returned null
, that would violate the contract of the second. And if the compiler allows it to be inherited in class C, then class C is effectively violating one of the implemented interfaces' contract, possibly leading to a bug without the programmer's attention.
Note that if B were a class rather than interface, then there is no issue at compilation, because the issue of "mixed contract" is not present in this case, as there is only one interface.