Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Inheritance Ambiguity with Interface

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?

like image 663
Razib Avatar asked Apr 20 '15 20:04

Razib


People also ask

Is multiple inheritance possible in interface?

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.

How does interface solve the problem of multiple inheritance?

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.

Why there is no ambiguity in interface in Java?

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.


1 Answers

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.

like image 68
Daniel Pryden Avatar answered Sep 23 '22 09:09

Daniel Pryden