派生类如何调用基类的私有方法?
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 的私有方法?
回答:
因为您在PrivateOverride类中定义了main方法。如果将main方法放在Derived类中,它将无法编译,因为在该类中.f()不可见。
class中的po.f()调用PrivateOverride不是多态的,因为f()in
PrivateOverride类为private,所以f()in Derivedclass中的值不会被覆盖。
以上是 派生类如何调用基类的私有方法? 的全部内容, 来源链接: utcz.com/qa/405395.html



