在下面的代码中,子类"B"中名为"x"的实例变量隐藏了在父超类"A"中也称为"x"的实例变量.
public class A {
public int x;
}
public class B extends A {
public int x;
}
Run Code Online (Sandbox Code Playgroud)
在下面的代码中,为什么println(zx)显示零值?谢谢.
A a = new A();
B b = new B();
a.x = 1;
b.x = 2;
A z = b;
System.out.println(z.x); // Prints 0, but why?
Run Code Online (Sandbox Code Playgroud)
在下面的代码中,为什么 println(zx) 显示值为零?
因为它引用的是...x中声明的字段,A所以这是唯一z.x 可以引用的字段,因为 的编译时类型z是A。
您创建的实例B有两个字段:在中声明的字段A(其值为 0)和在中声明的字段B(其值为 2)。您创建的实例A完全无关;它是一个完全独立的对象。
这是一个很好的理由:
| 归档时间: |
|
| 查看次数: |
222 次 |
| 最近记录: |