接口和inheritance:“返回类型int不兼容”

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它给了我错误

接口中的java:myMethod()在interfaceRnD.DerivedClass中不能覆盖interfaceRnD.SuperClass中的myMethod()
  返回类型int与java.lang.String不兼容

我该如何解决这个问题?

这个错误是因为对myMethod的调用不明确 – 应该调用哪两种方法? 来自JLS§8.4.2 :

在类中声明具有覆盖等效签名的两个方法是编译时错误。

方法的返回类型不是其签名的一部分,因此您将根据上述语句收到错误。

假设您不能简单地重命名冲突的方法,在这种情况下您不能使用inheritance,并且需要使用类似组合的替代方法:

 class DerivedClass implements MyInterface { private SuperClass sc; public String myMethod1() { return sc.myMethod(); } public int myMethod() { return 0; } } 

您不能拥有两个具有相同签名但返回类型不同的方法。

这是因为当你执行object.myMethod();时,编译器无法知道你试图调用哪个方法object.myMethod();

方法重载由它们的参数区分。 这里接口和超类中的myMethod()具有类似的参数签名。 所以你不能这样做。

您不能拥有2个具有相同签名但具有不同返回类型的方法。 如果可能,则无法确定是否调用了方法。

BTW界面中的所有方法都是publicabstract

 public interface MyInterface{ int myMethod(); } 

你可以做的是有一个带输入参数的接口,这称为overloading

例:

  public interface MyInterface{ String myMethod(String param); } and in your class public class DerivedClass extends SuperClass implements MyInterface{ public String myMethod(){ ...} public String myMethod(String param) {...} }