javainterfaceoverridinginterface-implementation

why can't we implement two interfaces that have methods with identical signature which one of them has a default implementation in java?


Imagine that we have two interfaces which both have method display() with identical signatures. So far so good. Now I define a default implementation for one of them. Now when I want to implement both of them in my class, it gives me a syntax error. Can anyone help me understand the reason?

For example in the code below,

interface Show1 {
    default void display() {
        System.out.println("hello");
    }
}

interface Show2 {
    void display();
}

public class Person implements Show1, Show2 {

    public static void main(String args[]) {
        Person p = new Person();
        p.display();
    }
}

I thought that it would print hello because we have the default implementation. And since the two methods in the interfaces doesn't have any interference with each other. But it gives me syntax error. I would be thankful if you help me find the reason behind this behavior.


Solution

  • That is because the designers of Java decided that if you have two or more interfaces with the same (or override-equivalent) method signature, and one or more have a default implementation, then you must implement it yourself (that is, it behaves as if there is no default method, just an abstract method).

    That implementation could simply be the invocation of the default implementation of one of the interfaces.

    For example:

    interface Show1 {
        default void display() {
            System.out.println("hello");
        }
    }
    
    interface Show2 {
        void display();
    }
    
    public class Person implements Show1, Show2 {
    
        public static void main(String args[]) {
            Person p = new Person();
            p.display();
        }
    
        @Override
        public void display() {
            Show1.super.display();
        }
    }
    

    This is not something that happened by accident, this is something that was explicitly and intentionally designed and specified, specifically by 8.4.8 Inheritance, Overriding, and Hiding of The Java 17 Language Specification.