【问题标题】:return type int is not compatible with long error in java返回类型 int 与 java 中的长错误不兼容
【发布时间】:2020-12-05 06:44:15
【问题描述】:

我正在使用两个具有相同方法签名的接口并尝试在名为 Parent 的类中实现 和孩子。但是,我很困惑为什么协变返回类型在这里不起作用。

    interface First
    {
         public long show();
    }
    
    interface Second
    {
        public int show();
    }
    
    
    abstract class Parent implements First,Second
    {
        public long show(){
            return 10L;
        }
    }
    
    
    class Child extends Parent
    {
        public int show(){
            return 10;
        }
    }
    
    I get the following errors after compilation
    
    
      error: show() in Parent cannot implement show() in First
        public int show(){
                   ^
     return type int is not compatible with long
    error: show() in Child cannot implement show() in Second
        public long show(){
                    ^
  return type long is not compatible with int
                        ^
      return type long is not compatible with void
    
      But why int is not compatible with long? 
     
      

【问题讨论】:

  • “协变返回类型仅适用于非原始返回类型。” - 参见例如tutorialspoint.com/Covariant-return-types-in-Java
  • 你查看this 的帖子了吗?
  • @Swati 这个帖子没有涵盖我的问题
  • 不要完全更改现有问题。如果您有新问题,请创建一个新问题。
  • 强烈反对更改现有问题的规则。该项目的目标是创建一个问题及其答案的数据库。通过更改问题而不是创建新问题,您正在颠覆这一点。另外,在你把问题改得这么彻底之后,你原来的问题的答案会显得很傻。

标签: java


【解决方案1】:

协变返回类型在Language Spec 中描述:

如果返回类型是引用类型,则返回类型可能会因相互覆盖的方法而异。 return-type-substitutability 的概念支持协变返回,即将返回类型特化为子类型。

如果以下任何一项为真,则返回类型为 R1 的方法声明 d1 可替代返回类型为 R2 的另一个方法 d2:

  • 如果 R1 无效,则 R2 无效。
  • 如果 R1 是原始类型,则 R2 与 R1 相同。
  • 如果 R1 是引用类型,则以下情况之一为真:...

int 是比long 更窄的类型,但由于它是原始类型但与long 不同,因此不被视为可替换返回类型。

【讨论】:

    猜你喜欢
    • 2011-08-26
    • 2021-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    • 2016-05-28
    • 1970-01-01
    • 2013-09-23
    相关资源
    最近更新 更多