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?
An interface contains variables and methods like a class but the methods in an interface are abstract by default unlike a class. Multiple inheritance by interface occurs if a class implements multiple interfaces or also if an interface itself extends multiple interfaces.
Interfaces contain only public constant definitions and method headers. Interfaces can only extend other interfaces, not classes. Interfaces can extend multiple interfaces, and classes can implement multiple interfaces.
If B & C are interfaces, then there is no implementation in the interfaces. Even if B & C override the method in interface A (cannot be a class), the methods will have same signature. There is no ambiguity regarding which implementation to use, because there is no implementation.
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.
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