2013-05-23

Java 8: Default Interface Implementations, The Diamond Problem, Multiple Inheritance, and Precedence

If you understand the following cases, you understand Java 8' new interface model.

The code below, won't compile throwing this error:
java: class FooBar inherits unrelated defaults for someMethod() from types Foo and Bar
IntelliJ Screen Shot
Java 8: Won't compile

IntelliJ Screen Shot
Java 8: Compiles

The code above compiles and prints:
FooBar#main
FooBar#someMethod()
Foo#someOtherMethod()

The code below won't compile as well and throws this familiar (for Java < 8 JDKs) error message:
java: FooBar is not abstract and does not override abstract method someMethod() in Foo
IntelliJ Screen Shot
Java 8: Won't compile

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. Also if the class implements an interface's default method, the implementation of the class will be used instead of interfaces's default implementation.

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.

1 comment:

Sebastian Zarnekow said...

I don't think that the compiler patches some class files but the method lookup in the JVM was changed instead. Otherwise all existing code had to be recompiled as soon as a default method was added to an implemented interface.