【发布时间】:2018-03-27 11:08:09
【问题描述】:
我在理解什么是类之间的方法被调用的层次结构时遇到了问题。我这里有这段代码:
class X {
protected int v = 0;
public X() {
v = v + 10;
}
public void proc(X p) {
System.out.println(43);
}
}
class Y extends X {
public Y() {
v = v + 5;
}
public void proc(X p) {
System.out.println(57);
}
public int getV() {
return v;
}
}
class Z extends Y {
public Z() {
v = v + 9;
}
public void proc(Z p) {
System.out.println(39);
}
}
class Main {
public static void main(String argv[]) {
X x = new Z();
Y y = new Z();
Z z = new Z();
x.proc(z);
System.out.println(y.getV());
}
}
代码打印的数据是57 24。因此,在这种情况下,方法 proc 是在 X 引用但 Z 实例的对象上调用的,所以我认为将调用 X 类中的方法,但显然它调用了 Y 类中的方法。这是为什么呢?
非常感谢。
【问题讨论】:
-
啊哈,严重的骗局.. 否决
标签: java class methods hierarchy