【发布时间】:2015-11-11 08:51:43
【问题描述】:
在阅读有关嵌套类的 Oracle 文档时,我发现这段代码的输出我无法理解。有人可以解释一下吗?
public class ShadowTest {
public int x = 0;
class FirstLevel {
public int x = 1;
void methodInFirstLevel(int x) {
System.out.println("x = " + x);
System.out.println("this.x = " + this.x);
System.out.println("ShadowTest.this.x = " + ShadowTest.this.x);
}
}
public static void main(String... args) {
ShadowTest st = new ShadowTest();
ShadowTest.FirstLevel fl = st.new FirstLevel();
fl.methodInFirstLevel(23);
}
}
以下是该示例的输出:
x = 23
this.x = 1
ShadowTest.this.x = 0 //why is 0 printed here? why not 1 because "this" is the object of FirstLevel class.
原代码可以在here找到
【问题讨论】:
-
你到底有什么不明白的?请解释更多。
-
有什么问题 - 你不明白所有的输出,只有一个?
-
在
this前加上一个封闭类的名称,例如ShadowTest.this.x,会导致它引用封闭的对象。 -
ShadowTest.this.x 的输出我没看懂。
-
@RishabhGour - 查看将使用的
field取决于调用它的引用。ShadowTest.this.x表示访问ShadowTest'sx