【发布时间】: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()inBase是private,它不能被覆盖,因为它在子类中不可见,所以你最终要做的是定义第二个方法碰巧同名。由于第二种方法独立于所有其他方法,因此它的返回值没有限制。
标签: java access-modifiers overriding