How does Java 8' new default interface model works (incl. diamond, multiple inheritance, and precedence)?
How does this new interface model works and what is about
- the diamond problem that might arise out of this
- multiple inheritance character of this implementation
- and the precedence with which the interface implementations are used ?
Solution 1:
There is a perfect explanation at Java Lambda FAQ.
Here is a citation from What about the diamond problem? article there:
interface A {
default void m() { ... }
}
interface B extends A {}
interface C extends A {}
class D implements B, C {}
In the initial case (the code above), the implementation of m inherited by D is unambiguously that defined by A — there is no other possibility. If the situation is changed so that B now also declares a default implementation of m, that becomes the implementation that D inherits by the “most specific implementation” rule. But if both B and C provide default implementations, then they conflict, and D must either use the syntax X.super.m(...) to explicitly choose one of them, or else redeclare the method itself, overriding all supertype declarations.
Be sure to check out previous article on rules of resolving conflicting method declarations and other articles on Java Lambda project — they are quite good.
Solution 2:
Here is a detailed explanation for Java 8' new interface model & the diamond problem of multiple inheritance.
As you might see in this examples, starting with JDK 8, Java has introduced a kind of multiple inheritance as both, the class and its interface might contain an implementation of the same method (same name & signature). To address the diamond problem there is a precedence in which order an implementation is used: only if the class implements all default / optional methods of its interfaces, the code can be compiled and the implementations of this class are used. Otherwise the compiler tries to patch the missing implementation(s) with interface's default implementation. And if there are multiple default implementations of a method, then the diamond problem occurs and the compiler rejects the compilation.
Java 8' new interfaces model is the result of approaching backwards compatibility, i. e. to keep existing code that was written against pre Java 8 interfaces compilable.