java – 接口和继承:“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它给我的错误

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

我该怎么解决这个问题?

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

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

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

假设你不能简单地重命名冲突的方法,在这种情况下你不能使用继承,并且需要使用像composition这样的替代方法:

class DerivedClass implements MyInterface {

    private SuperClass sc;

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

    public int myMethod() {
        return 0;
    }

}
http://stackoverflow.com/questions/17152967/interface-and-inheritance-return-type-int-is-not-compatible

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:java – 接口和继承:“return type int is not compatible”