【问题标题】:Method Overridding Access modifier and Return Type Restriction方法覆盖访问修饰符和返回类型限制
【发布时间】:2014-07-31 09:44:08
【问题描述】:

以下代码根据方法覆盖的规则工作并显示编译错误 Incompatible return type with Base.aMethod()

class Base
{
    Integer aMethod()
    {
        return 0;
    }
}
public class OverRidingRules extends Base
{
    protected Number aMethod()
    {
        return 0;
    }
}

但是,如果我将 Base.aMethod 的访问修饰符从默认更改为私有,它将成功编译。谁能告诉我为什么编译器没有显示同样的错误?

【问题讨论】:

  • 如果aMethod() in Baseprivate,它不能被覆盖,因为它在子类中不可见,所以你最终要做的是定义第二个方法碰巧同名。由于第二种方法独立于所有其他方法,因此它的返回值没有限制。

标签: java access-modifiers overriding


【解决方案1】:

覆盖方法不能有比它覆盖的方法“更宽”的返回类型1,这就是你在这里所做的。来自BaseaMethod只能返回Integer,因此用可以返回任何Number 的东西覆盖它是无效的,例如Floats。这就是您在当前代码中收到编译错误的原因。

现在,当您将 Base 中的 aMethod 更改为 private 时,将无法再在子类中看到/覆盖它。因此,在这种情况下,OverRidingRules 中的aMethod 并没有覆盖Base 中的aMethod,而是一个同名的独立方法,因此我们不会遇到与上述相同的问题,也不会出现编译错误.

@user3580294his comment 中也指出了这一切。


1 然而,反过来也是有效的。例如,以下内容是合法的:

class Base {
    Number aMethod() {   // notice the return type is `Number`
        return 0;
    }
}

class OverRidingRules extends Base {
    Integer aMethod() {  // notice the return type is `Integer`
        return 0;
    }
}

换句话说,覆盖方法可以具有比它覆盖的方法“更窄”的返回类型。

【讨论】:

  • 感谢您的回答,但对我的问题的第一条评论完美地回答了我的问题。
猜你喜欢
  • 2012-11-07
  • 1970-01-01
  • 2015-11-27
  • 2013-07-09
  • 2013-03-17
  • 2017-12-19
  • 2020-02-05
  • 1970-01-01
  • 2012-12-21
相关资源
最近更新 更多