【发布时间】:2014-07-14 08:45:08
【问题描述】:
我不明白为什么这段代码的输出是10:
package uno;
public class A
{
int x = 10;
A(){int x = 12; new B();}
public static void main(String args[]){
int x = 11;
new A();
}
class B{
B(){System.out.println(x);}
}
}
此示例中的作用域如何工作?为什么System.out.println(x); 打印 10?是不是因为指令 System.out.println(x); 不在 costructor 的括号内:A(){int x=12; new B();} 所以 int x = 12 只存在于那里,但当 System.out.println(x); 被调用时,x = 12 不再存在?那么第一个x 是在A 类中声明的x=10?如果A 类中有x 怎么办?它会打印11吗?
【问题讨论】:
-
如果 A 类中有 x 怎么办?
x是 在A中。 -
您正在 A() 中创建另一个变量,并且您没有修改该字段。在 A() 中尝试 x = 12。