Lets say I have the following structure:
abstract class A {
abstract boolean foo();
}
interface B {
default boolean foo() { return doBlah(); }
}
class C extends A implements B {
//function foo
}
Java will now complain that class C
must implement abstract method foo from A
.
I can work around this problem relatively easy by redefining the function in C
and simply calling B.super.foo();
.
however I do not understand why the default function from interface B
does not forfill this requirement on its own, and I would like to have a better understanding of the underlying mechanics of java.
Extending Interfaces That Contain Default MethodsRedeclare the default method, which makes it abstract .
Abstract class in Java is similar to interface except that it can contain default method implementation. An abstract class can have an abstract method without body and it can have methods with implementation also. abstract keyword is used to create a abstract class and method.
The purpose of the default method is to provide external functionality without breaking the existing implementations. The original motivation behind introducing the default method was to provide backward compatibility to the Collection Framework with the new lambda functions.
Default interface methods enable an API author to add methods to an interface in future versions without breaking source or binary compatibility with existing implementations of that interface. The feature enables C# to interoperate with APIs targeting Android (Java) and iOS (Swift), which support similar features.
Default methods in Interfaces are used to prevent breaking programs that depend on your Interface when you add a method to your Interface.
In the case you describe, it is unclear if the default method in the interface (which by design must have been added later on) actually fulfills the contract as originally envisioned by the Abstract Class.
In this case it is safer for Java to complain.
Above text is my interpretation of the paragraph in 9.4.1.3 of the JLS SE8 spec, and I quote:
Similarly, when an abstract and a default method with matching signatures are inherited, we produce an error. In this case, it would be possible to give priority to one or the other - perhaps we would assume that the default method provides a reasonable implementation for the abstract method, too. But this is risky, since other than the coincidental name and signature, we have no reason to believe that the default method behaves consistently with the abstract method's contract - the default method may not have even existed when the subinterface was originally developed. It is safer in this situation to ask the user to actively assert that the default implementation is appropriate (via an overriding declaration).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With