l***r 发帖数: 459 | 1 I have two pieces of code
1) has compilation error:
class TestScope {
public void test() {
int x = 2;
if ( true ) {
int x = 1;
System.out.println( "In if: " + x );
}
System.out.println( "Out If: " + x );
}
}
2) compiled and output is: In if: 1 Out If: 2
class TestScope {
int x = 2;
public void test() {
if ( true ) {
int x = 1;
System.out.println( "In if: " + x );
}
System.out.println( "Out If: " + x );
}
}
Can you tell me why Java support this differently?
Thanks! | n*****k 发帖数: 123 | 2
~~~~~~~~~~~~
here is the compilation error
Because in the first example, there is no instance varible(or class variable)
nameed x exists other than the local varibale inside the method, so the scope
of the x is all over the method, and it can not be shadowed any other local
variable inside the method.
On the other hand, the second example has an instance variable x and also a
local block variable x, inside the if block, the local variable
【在 l***r 的大作中提到】 : I have two pieces of code : 1) has compilation error: : class TestScope { : public void test() { : int x = 2; : if ( true ) { : int x = 1; : System.out.println( "In if: " + x ); : } : System.out.println( "Out If: " + x );
| h******b 发帖数: 312 | 3 Nod, agree, very clear explanation!
variable)
scope
【在 n*****k 的大作中提到】 : : ~~~~~~~~~~~~ : here is the compilation error : Because in the first example, there is no instance varible(or class variable) : nameed x exists other than the local varibale inside the method, so the scope : of the x is all over the method, and it can not be shadowed any other local : variable inside the method. : On the other hand, the second example has an instance variable x and also a : local block variable x, inside the if block, the local variable
|
|