派生类如何调用基类的私有方法? [英] How can a derived class invoke private method of base class?
问题描述
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()
。现在,问题出现在我的脑海中:作为 Derived 类的对象的 po 如何调用 PrivateOverride 的私有方法,这是它的基础class?
So, the output of this code is private f()
. Now, the question arises to my mind: how can po which is an object of Derived Class call a private method of PrivateOverride which is its base class?
推荐答案
因为您在 PrivateOverride
类中定义了main方法。如果你把main方法放在Derived类中,它就不会编译,因为那里不会显示 .f()
。
Because you defined the main method in PrivateOverride
class. If you put the main method in Derived class, it would not compile, because .f()
would not be visible there.
po.f()调用 PrivateOverride
类不是多态,因为 f()
in PrivateOverride
class private
,所以 f()
in 派生的
类未被覆盖。
po.f() call in PrivateOverride
class is not a polymorphism, because the f()
in PrivateOverride
class is private
, so f()
in Derived
class is not overriden.
这篇关于派生类如何调用基类的私有方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!