Can any one explain why the following is not allowed in Java int x; // outer scope { int x; // inner scope } One would assume that this should work. Thanks SRA
Li Yang
Greenhorn
Joined: Sep 28, 2000
Posts: 7
posted
0
The outer scope variable x is accessible inside the inner scope, hence you have a name conflict when you define the inner variable x.
Prasad Ballari
Ranch Hand
Joined: Sep 23, 2000
Posts: 149
posted
0
sriranch, Can u pls give me little more detailed code.coz,u can have a class variable and instance variable of same name but with different scope. Prasad ------------------
Jane Griscti
Ranch Hand
Joined: Aug 30, 2000
Posts: 3141
posted
0
Hi sriranch, Well, it does work, to a point. It depends on the context. For example, it works fine in this code:
However, it won't work in the following context:
The answer is in JLS §14.4.2
The name of a local variable v may not be redeclared as a local variable of the directly enclosing method, constructor or initializer block within the scope of v, or a compile-time error occurs.
sriranch, This probably will not help much but the JLS(Second Edition) simply states on page 281 that "if a declaration of an identifier as a local variable of the same method, constructor, or initializer block appears within the scope of a parameter or local variable of the same name, a compile-time error occurs". Also, the only reason provided on page 282 is that "this restriction helps to detect some otherwise very obscure bugs". Hope this helps. Bob Kerfoot - SCJP