我不明白为什么这段代码的输出是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);
在构造函数的括号之外:A(){int x=12; new B();}
等等int x = 12
只生活在那里,但当 System.out.println(x);
被调用,x = 12
不再活了??所以第一个x
是 x=10
在类中声明A
?如果有的话怎么办x
上课A
?它会打印 11
?
最佳答案
局部变量只能从声明它们的方法中访问。考虑到这一点,可以重写代码以避免 shadowing the member variables以及由此产生的困惑:
package uno;
public class A{
// And instance member variable (aka field)
int field_A_x = 10;
A(){
// A local variable, only visible from within this method
int constructor_x = 12;
new B(); // -> prints 10
// Assign a new value to field (not local variable), and try again
field_A_x = 12;
new B(); // -> prints 12
}
public static void main(String args[]){
// A local variable, only visible from within this method
int main_x = 11;
new A();
}
class B{
B(){
// The inner class has access to the member variables from
// the parent class; but the field not related to any local variable!
System.out.println(field_A_x);
}
}
}
(隐藏的成员变量始终可以通过 this.x
表示法进行访问;但我建议不要隐藏变量 - 选择有意义的名称。)
关于Java 变量的作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24732644/