public class PrivateOverride {
private void f() {
System.out.println("private f()");
}
}
public class Derived extends PrivateOverride {
public void f() { //this method is never run.
System.out.println("public f()");
}
}
public static void main(String[] args) {
// instantiate Derived and assign it to
// object po of type PrivateOverride.
PrivateOverride po = new Derived();
// invoke method f of object po. It
// chooses to run the private method of PrivateOveride
// instead of Derived
po.f();
}
}
因此,此代码的输出为
private f()
。现在,我想到了一个问题:作为派生类对象的po怎么能调用作为基类的PrivateOverride的私有(private)方法? 最佳答案
因为您在PrivateOverride
类中定义了main方法。如果将main方法放在Derived类中,则它将无法编译,因为.f()
在此处不可见。PrivateOverride
类中的po.f()调用不是多态的,因为f()
类中的PrivateOverride
是private
,因此f()
类中的Derived
不被覆盖。