Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does order of implementing Interfaces (with default methods) matter in Java 8?

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.

like image 500
Pradip Kharbuja Avatar asked Sep 19 '15 02:09

Pradip Kharbuja


People also ask

Why do we need default method in Java 8 interfaces?

Default methods were introduced to provide backward compatibility for old interfaces so that they can have new methods without affecting existing code.

Can we override default method in Java interface 8?

A default method cannot override a method from java.

What is the use of default methods in Java 8?

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.

What is the purpose of default method in interface?

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.


1 Answers

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?

like image 164
dkatzel Avatar answered Sep 30 '22 14:09

dkatzel