Java Reference
In-Depth Information
parameter of a
catch
clause in a
try
statement of the directly enclosing method or initializer
block.
The translation of a
try
-with-resources statement implies the rule above.
Despite the above rules against redeclaration of variables, the rules of shadowing
• A formal parameter of a method or constructor may be shadowed anywhere
inside a class declaration nested within that method or constructor.
• A local variable of a method, constructor, or initializer may be shadowed
anywhere inside a class declaration nested within the scope of the local vari-
able.
• A local class declaration may be shadowed anywhere inside a class declara-
tion nested within the local class declaration's scope.
• An exception parameter may be shadowed anywhere inside a class declara-
tion nested within the
Block
of the
catch
clause.
• A variable declared in a
ResourceSpecification
may be shadowed anywhere
inside a class declaration nested within the
try
Block
.
Example 6.4-1. Attempted Shadowing Of A Local Variable
Because a declaration of an identifier as a local variable of a method, constructor, or
initializer block must not appear within the scope of a parameter or local variable of
the same name, a compile-time error occurs for the following program:
class Test1 {
public static void main(String[] args) {
int i;
for (int i = 0; i < 10; i++)
System.out.println(i);
}
}
This restriction helps to detect some otherwise very obscure bugs. A similar restric-
tion on shadowing of members by local variables was judged impractical, because the
addition of a member in a superclass could cause subclasses to have to rename loc-
al variables. Related considerations make restrictions on shadowing of local variables