As we all know, multiple interfaces
can implemented in Java. Does the order of their implementation matter? I mean, is implementing B, C is same as C, B in Java 8
? My tests show order does matter - but can anyone explain the logic behind this?
public interface A {
public default void display() {
System.out.println("Display from A");
}
}
public interface B extends A {
public default void display() {
System.out.println("Display from B");
}
}
public interface C extends A {
public void display();
}
public interface D extends B, C {
}
The above code works fine. If I change the order B, C
to C, B
, it will give an error: The default method display() inherited from B conflicts with another method inherited from C.
public interface D extends C, B {
}
Edit
I am using Eclipse(Mars). JDK jdk1.8.0_51
. JRE jre1.8.0_60
.
Default methods were introduced to provide backward compatibility for old interfaces so that they can have new methods without affecting existing code.
A default method cannot override a method from java.
Default methods in Java 8 also known as defender methods allow Java developers to add new methods to the existing interfaces in their code without breaking their current implementation.
Default methods enable you to add new functionality to existing interfaces and ensure binary compatibility with code written for older versions of those interfaces. In particular, default methods enable you to add methods that accept lambda expressions as parameters to existing interfaces.
There should be an error message either way. When I use jdk 1.8.0_31 I get the following error no matter the order of interfaces:
The default method display() inherited from A.B conflicts with another method inherited from A.C
The solution is to either override display()
in D
even to just tell the compiler which super class's implementation to use:
public interface D extends B, C {
default void display(){
B.super.display();
}
}
Or remake display()
abstract
interface D extends B, C {
public void display();
}
If you are indeed getting this error using a higher version than me, then it might be worth submitting a bug report?
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