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!");
    }
}
3
  • 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 ? Commented Apr 7, 2022 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. Commented Apr 7, 2022 at 16:39
  • @juzraai, thank you for your answer. It partially resolved my doubts, and additionally I also followed this (stackoverflow.com/questions/16207386/…) answer to understand more about override equivalency! Commented Apr 7, 2022 at 17:12

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.