我在一本书中看到了一段代码,如下:
x = 10;
if(x ==10) { // start new scope
int y = 20; // known only to this block
x = y * 2;
}
Run Code Online (Sandbox Code Playgroud)
代码和块都是一样的吗?
Moh*_*mel 13
范围是您可以引用变量的位置.块定义块内定义的block scope变量将仅在块内定义,并且在块结束后不能引用它.
所以在这段代码中如果你尝试类似的东西:
x = 10;
if(x ==10) { // start new scope
int y = 20; // known only to this block
x = y * 2;
}
y = 5; // error y is out of scope, not it is not defined
Run Code Online (Sandbox Code Playgroud)
因为你在这里有一个本地范围
java中的其他种类范围class scope(例如),类的成员具有类范围,因此可以在类中的任何位置访问它.
范围的基本规则是: