【问题标题】:interface and inheritance: "return type int is not compatible"接口和继承:“返回类型 int 不兼容”
【发布时间】:2013-06-17 17:04:27
【问题描述】:
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:interfaceRnD.DerivedClass 中的 myMethod() 无法覆盖 interfaceRnD.SuperClass 中的 myMethod() 返回类型 int 与 java.lang.String 不兼容

我应该如何解决这个问题?

【问题讨论】:

  • 现在听起来很有趣
  • 那么public String myMethod() {...} 真的有问题吗?据我了解,唯一的问题是紧随其后的线路。我错过了什么吗?

标签: java inheritance interface


【解决方案1】:

错误是由于对myMethod 的调用不明确——应该调用这两种方法中的哪一种?来自JLS §8.4.2

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

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

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

class DerivedClass implements MyInterface {

    private SuperClass sc;

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

    public int myMethod() {
        return 0;
    }

}

【讨论】:

  • 我得到了你 arshajii ...非常感谢您的解决方案..我更喜欢作文 ....非常感谢 agian...
【解决方案2】:

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

这是因为当您执行object.myMethod(); 时,编译器无法知道您尝试调用的方法。

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

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

      顺便说一句,接口中的所有方法都是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) {...}   
             }  
      

      【讨论】:

        猜你喜欢
        • 2015-09-01
        • 2012-05-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多