接口和继承:“返回类型int不兼容” [英] interface and inheritance: "return type int is not compatible"
问题描述
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
}
当我尝试编译 DerivedClass
时,它给了我错误
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?
推荐答案
该错误是由于对<$的调用造成的c $ c> myMethod 将不明确 - 应该调用哪两种方法?来自JLS§8.4.2:
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:
在类中使用覆盖等效签名声明两个方法是一个编译时错误。
方法的返回类型不是其签名的一部分,因此您收到的错误是根据上面的陈述。
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;
}
}
这篇关于接口和继承:“返回类型int不兼容”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!