接口和继承:"返回类型int不兼容"

Jal*_*eri 19 java inheritance interface

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
}
Run Code Online (Sandbox Code Playgroud)

当我尝试编译时,DerivedClass它给了我错误

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

我该如何解决这个问题?

ars*_*jii 22

这个错误是因为调用myMethod是模糊的 - 应该调用哪两个方法?来自JLS§8.4.2:

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

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

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

class DerivedClass implements MyInterface {

    private SuperClass sc;

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

    public int myMethod() {
        return 0;
    }

}
Run Code Online (Sandbox Code Playgroud)

  • +1用于推荐*如何*部分的组合. (5认同)
  • +1引用语言规范 (2认同)

Ema*_*gan 12

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

这是因为编译器无法知道您在尝试调用的方法object.myMethod();.