Amo*_*wal 4 java methods overriding
class One {
void foo() { }
}
class Two extends One {
private void foo() { /* more code here */ }
}
Run Code Online (Sandbox Code Playgroud)
为什么上面的代码片段错了?
coo*_*ird 11
我将尝试将其他答案中的想法结合起来,得出一个答案.
首先,我们来看看代码中发生了什么.
看一下代码
本One类有一个包私有foo方法:
class One {
// The lack of an access modifier means the method is package-private.
void foo() { }
}
Run Code Online (Sandbox Code Playgroud)
在Two该子类的类One的类,并且所述foo方法被重写,但是具有访问修饰符private.
class Two extends One {
// The "private" modifier is added in this class.
private void foo() { /* more code here */ }
}
Run Code Online (Sandbox Code Playgroud)
问题
Java语言不允许子类降低子类中方法,字段或类Two的可见性,因此,降低foo方法可见性的类是不合法的.
为什么降低能见度是个问题?
考虑我们想要使用One该类的情况:
class AnotherClass {
public void someMethod() {
One obj = new One();
obj.foo(); // This is perfectly valid.
}
}
Run Code Online (Sandbox Code Playgroud)
在这里,调用实例foo上的方法One是有效的.(假设AnotherClass该类与该类位于同一个包中One.)
现在,如果我们要实例化Two对象并将其放在obj类型的变量中,该One怎么办?
class AnotherClass {
public void someMethod() {
One obj = new Two();
obj.foo(); // Wait a second, here...
}
}
Run Code Online (Sandbox Code Playgroud)
该Two.foo方法是私有的,但该One.foo方法允许访问该方法.我们在这里遇到了问题.
因此,在考虑继承时允许降低可见性没有多大意义.
链接