0

This is my first post in SO. I have a scenario where there are two interfaces X & Y, each having one abstract method foo() with different return types (String in interface X and void in interface Y).

When I implement both these interfaces in a single class, then by default, I need to provide implementation of foo(). Now, since the method name is same in both the interfaces, Java is only allowing me to implement the method once (not twice with different return types as I would think).

As a result, I am getting error:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: The return type is incompatible with X.foo()

If I'm implementing foo() with String return type.

And similarly, with void foo() implementation, I'm getting:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: The return type is incompatible with Y.foo()

To me it seems to be an unsolvable problem as of now. Is there any way out of it?

Following is my code:

interface X {
    String foo();
}

interface Y {
    void foo();
}

public class InterfaceClassDemo implements X,Y {

    public static void main(String[] args) {
        System.out.println("Inside main!");
        new InterfaceClassDemo().foo(); 
    }

    @Override
    public String foo() {
        System.out.println("Inside foo!");
    }
}
  • 1
    Look at it this way. You have two methods that differ only in their return value. If I call your method and don't collect the return value, which would I expect to be called ? – Brian Agnew Apr 07 '22 at 16:30
  • Return types are not part of a methods signature. So the same methods with the same `names` and `arguments` are basically the same method. Therein lies at least part of the since you can't implement both. – WJS Apr 07 '22 at 16:39
  • @juzraai, thank you for your answer. It partially resolved my doubts, and additionally I also followed this (https://stackoverflow.com/questions/16207386/what-is-override-equivalence-and-how-is-it-related-to-override) answer to understand more about override equivalency! – Parag Acharyya Apr 07 '22 at 17:12

0 Answers0