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?
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With