因为:
可能会破坏parent class代码。例如考虑以下代码(obB.getInt();如果允许实例变量覆盖,则以下代码中的行的行为是什么):
class A
{
int aInt;
public int getInt()
{
return aInt;
}
}
class B extends A
{
int aInt;
public int getInt2()
{
return aInt;
}
public static void main(String[] args)
{
B obB = new B();
//What would be behavior in following line if,
//instance variables overriding is allowed
obB.getInt();
}
}
这是不合乎逻辑的,因为child class应该有/反映所有行为的parent class。
因此,您只能将继承的方法/变量隐藏在中,child class而不能override。
以下是Oracle Java文档的摘录,其中指定了可以执行/期望执行的操作child class:
您可以按原样使用继承的成员,替换它们,隐藏它们,或用新成员补充它们:
继承的字段可以像其他任何字段一样直接使用。
您可以在子类中声明一个与超类中的名称相同的字段,从而将其隐藏(不建议)。