Deadly Diamond of Death in Java 8

I am a Java developer and I am learning C ++ on the side. I recently hit the "deadly diamond of death" in C ++ and investigated if this problem was possible in Java. Are Interfaces Solving the "Deadly Diamond of Death" Question? , I found this:

Java 8 spins it for methods; now the interface can declare both default methods and static implementation methods. This brings a big chunk of the "Diamond of Death" problem to the tongue.

I am wondering if anyone will be able to extend the problems encountered in Java 8 for DDD.

+2
source share
2 answers

I believe the quoted answer refers to scenarios like this in Java: 1

interface B { default void x() { System.out.println("B::x"); } } interface C { default void x() { System.out.println("C::x"); } } class D implements B, C {} 

What will new D().x() do here?

Fortunately, the compiler completely prohibits the definition of D with the following message:

 D inherits unrelated defaults for x() from types B and C 

You can eliminate the ambiguity (and satisfy the compiler) by overriding x in D You can then explicitly call the individual inherited methods by default:

 class D implements B, C { @Override public void x() { B.super.x(); // Note explicit interface names C.super.x(); } } 

<sub> 1. It is clear that there is no diamond. But this is an even simpler case. We could add interface A { void x(); } interface A { void x(); } that both B and C expand, but this will not change the result.

+9
source

There are three resolution rules that prevent a diamond problem:

In Java-8 in an action book:

  • Classes always win. a method declaration in a class or a superclass takes precedence over any default method declaration.

  • Otherwise, sub-interfaces win: a method with the same signature is selected in the most specific interface by default. (If B continues to A , B more specific than A ).

  • Finally, if the choice is still ambiguous, a class that inherits from several interfaces must explicitly choose which default implementation of the method to use, overriding it and explicitly calling the desired method.

If for some reason some ambiguity remains, then your code simply will not compile.

+6
source

Source: https://habr.com/ru/post/1403320/


All Articles