Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

interface and inheritance: "return type int is not compatible"

Tags:

public interface MyInterface{
    public int myMethod();
}


public class SuperClass {
    public String myMethod(){
        return "Super Class";
    }
}

public class DerivedClass extends SuperClass implements MyInterface {
    public String myMethod() {...}  // this line doesn't compile 
    public int myMethod() {...}     // this is also unable to compile
}

When I try to compile DerivedClass it gives me the error

java: myMethod() in interfaceRnD.DerivedClass cannot override myMethod() in interfaceRnD.SuperClass
  return type int is not compatible with java.lang.String

How should I solve this issue?

like image 975
Jalpan Randeri Avatar asked Jun 17 '13 17:06

Jalpan Randeri


1 Answers

The error results from the fact that a call to myMethod will be ambiguous - which of the two methods should be called? From JLS §8.4.2:

It is a compile-time error to declare two methods with override-equivalent signatures in a class.

The return type of a method is not a part of its signature, so you are receiving an error in accordance with the statement above.

Assuming you can't simply rename the conflicting methods, you can't use inheritance in this case, and will need to use an alternative like composition:

class DerivedClass implements MyInterface {

    private SuperClass sc;

    public String myMethod1() {
        return sc.myMethod();
    }

    public int myMethod() {
        return 0;
    }

}
like image 197
arshajii Avatar answered Jan 03 '23 18:01

arshajii