2
interface A {
    default void m() {
        System.out.println("Hello from A");
    };
}

interface B extends A {
    default void m() {
        System.out.println("Hello from B");
    };


}

interface C extends A {

}

class D implements B, C {

}

public class Main {

    public static void main(String[] args) {
        D obj = new D();
        obj.m();
    }

}

I am unable to come to a decision why do i get an output..I have modeled this problem as diamond problem.. Is This model similar to Diamond Problem ? But It works Fine in Java .....Why?

RIshab R Bafna
  • 397
  • 1
  • 3
  • 7

3 Answers3

3

Default methods in java works like this: If no implementation was provided in the concrete class, it will default to the implementation of the method which is further down in the class hierarchy.

In your code, since B extends A, and C does not provide an implementation to m(), a class which implements B will default to B's implementation.

Stav Saad
  • 589
  • 1
  • 4
  • 13
0

"Interfaces give something similar to multiple inheritance, the implementation of those interfaces is singly (as opposed to multiple) inherited. This means that problems like the diamond problem – in which the compiler is confused as to which method to use – will not occur in Java."

Link

ltalhouarne
  • 4,586
  • 2
  • 22
  • 31
  • IMO a more complete answer would specifically address default methods that the OP is using in the question. – NPE Dec 04 '14 at 14:24
  • Can you elaborate your statement "Interfaces give something similar to multiple inheritance, the implementation of those interfaces is singly (as opposed to multiple) inherited" – RIshab R Bafna Dec 04 '14 at 14:28
  • It is my understanding that by extending multiple interfaces you can mimic the multiple inheritance, however you cannot implement multiple interfaces. – ltalhouarne Dec 04 '14 at 14:40
0

The reason why this example works is because Java's ability to implement methods in interfaces (using default) is explicitly designed to AVOID the issues that cause the diamond problem.

The diamond problem occurs in multiple inheritance when the inherited classes contains a state as it's not clear whether that state should be shared or separate for the different branches of the class hierarchy.

Java's interfaces, on the other hand, do not allow any state whatsoever, only methods. As such, as soon as it is implemented as a proper class (and thus can contain a state), it loses the multiple inheritance ability.

BambooleanLogic
  • 7,530
  • 3
  • 30
  • 56