令人困惑的“覆盖私人方法” [英] Confusing "override a private method"
问题描述
我对此代码有两个问题
public class Override {
private void f() {
System.out.println("private f()");
}
public static void main(String[] args) {
Override po = new Derived();
po.f();
}
}
class Derived extends Override {
public void f() {
System.out.println("public f()");
}
}
/*
* Output: private f()
*/// :~
1)如何在Override po的引用上看到函数f;
1) How is function f is visible on the reference of Override po;
2)为什么输出private f()
2) Why is output "private f()"
推荐答案
-
main
方法在类覆盖
中,所以当然它可以看到类的私有成员覆盖
。
The
main
method is inside classOverride
, so ofcourse it can see the private members of classOverride
.
您不重写方法 f
in class 派生
,没有多态。变量 po
的类型是覆盖
,因此它将采用方法 f
来自班级覆盖
。
You are not overriding method f
in class Derived
, there is no polymorphism. The type of the variable po
is Override
, so it will take method f
from class Override
.
请注意类中的方法
在超类中。 f
在类 Derived $ c $中根本看不到覆盖
C>。类派生
中的方法 f
是一种不同的方法,与方法<$没有任何关系c $ c> f
Note that method f
in class Override
is not visible at all in class Derived
. The method f
in class Derived
is a different method, that doesn't have anything to do with the method f
in the superclass.
这篇关于令人困惑的“覆盖私人方法”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!