14.3.3
Hiding of Names by Local Variables
BLOCKS AND STATEMENTS
which compiles correctly and produces the output:
2+1=3
The initializer for
three
 can correctly refer to the variable
two
 declared in an ear 
lier declarator, and the method invocation in the next line can correctly refer to the
variable
three
 declared earlier in the block.
The scope of a local variable declared in a
for
 statement is the rest of the
for
statement, including its own initializer.
If a declaration of an identifier as a local variable appears within the scope of
a parameter or local variable of the same name, a compile time error occurs. Thus
the following example does not compile:
class Test {
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
restriction on hiding of members by local variables was judged impractical,
because the addition of a member in a superclass could cause subclasses to have to
rename local variables.)
On the other hand, local variables with the same name may be declared in two
separate blocks or
for
 statements neither of which contains the other. Thus:
class Test {
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();
}
}
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
14.3.3   Hiding of Names by Local Variables
If a name declared as a local variable is already declared as a field or type name,
then that outer declaration is hidden throughout the scope of the local variable.
The field or type name can almost always ( 6.8) still be accessed using an appro 
priately qualified name. For example, the keyword
this
 can be used to access a
268






footer




 

 

 

 

 Home | About Us | Network | Services | Support | FAQ | Control Panel | Order Online | Sitemap | Contact

java hosting

 

Our partners: PHP: Hypertext Preprocessor Best Web Hosting Java Web Hosting Inexpensive Web Hosting  Jsp Web Hosting

Cheapest Web Hosting Jsp Hosting Cheap Hosting

Visionwebhosting.net Business web hosting division of Web Design Plus. All rights reserved