Java Reference
In-Depth Information
by members of nested classes, or on shadowing of local variables by local variables
declared within nested classes unattractive as well.
Hence, the following program compiles without error:
class Test2 {
public static void main(String[] args) {
int i;
class Local {
{
for (int i = 0; i < 10; i++)
System.out.println(i);
}
}
new Local();
}
}
On the other hand, local variables with the same name may be declared in two separ-
ate blocks or
for
statements, neither of which contains the other:
class Test3 {
public static void main(String[] args) {
for (int i = 0; i < 10; i++)
System.out.print(i + " ");
for (int i = 10; i > 0; i--)
System.out.print(i + " ");
System.out.println();
}
}
This program compiles without error and, when executed, produces the output:
0 1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
6.4.1. Shadowing
Some declarations may be
shadowed
in part of their scope by another declaration of the
same name, in which case a simple name cannot be used to refer to the declared entity.
Shadowing is distinct from hiding (§
8.3
,
§
8.4.8.2
, §
8.5
,
§
9.3
,
§
9.5
), which applies only to
members which would otherwise be inherited but are not because of a declaration in a sub-
class. Shadowing is also distinct from obscuring (§
6.4.2
).