Multiple Inheritance Ambiguity with Interface

Razib picture Razib · Apr 20, 2015 · Viewed 13.7k times · Source

We all know about the diamond problem regarding multiple inheritance -

   A
  / \
 B   C
  \ / 
   D

This problem describe an ambiguous situation for class D. If class A has a method and both/either of B and/or C override the method then which version of method does D override?

Is this problem also applicable for interfaces in Java? If not, how do Java interfaces overcome this problem?

Answer

Daniel Pryden picture Daniel Pryden · Apr 20, 2015

The diamond problem only applies to implementation inheritance (extends in all versions of Java prior to Java 8). It doesn't apply to API inheritance (implements in all versions of Java prior to Java 8).

Since interface methods with matching type signatures are compatible, there is no diamond problem if you inherit the same method signature twice: matching method signatures simply coalesce instead. (And if the type signatures aren't the same, then you don't have the diamond problem either.)

In Java 7 and below, the only way to inherit implementation code was via the extends keyword, which restricts to at most one parent. Therefore there is no multiple implementation inheritance and the diamond problem does not exist.

Java 8 adds a new wrinkle because it allows interfaces to have implementation code. It still escapes the diamond problem by simply falling back to the previous behavior (no implementation inheritance) when you're implementing multiple interfaces with methods that have matching signatures.