Java Reference
In-Depth Information
saying that variables that are declared at a higher level (locally in the method) can be accessed by a
lower level (a loop block within the method).
I close this section on variable scope—and variables in general—with a number of important remarks.
First, you might be wondering what happens whenever variables defined in different locations (that is,
at a different level of scope) clash in terms of naming. For example, consider the following example:
class ScopeTest {
int a = 5;
void printA() {
int a = 10;
System.out.println("The value of a is now: "+a);
}
}
What will show up when the method printA is called? Again, remembering that rule that higher‐
level variables can be accessed from lower‐level locations provides some guidance here, as accessing
a variable will “bubble up” from the current scope. This means that Java will first try to access the
variable locally, and then move outward until looking for instance variables or static class variables
bearing the requested name. This means that in the previous example, the local variable gets pre-
cedence and the result displaying on the screen will thus be 10. This concept is known as “variable
shadowing” (consider the local variable to overshadow the higher‐level ones). Keep this in mind
when naming variables. Note also that Eclipse will provide subtle formatting and coloring hints to
indicate which variable is being accessed.
Note What if you really wanted to access the instance variable and not the local
variable in this example, without renaming one of them? In that case, you have to
explicitly tell Java you want the instance variable, using the keyword this , like so:
class ScopeTest {
int a = 5;
void printA() {
int a = 10;
System.out.println("The value of INSTANCE VARIABLE " +
"a is now: "+this.a);
}
}
And when a is a class variable, remember to use the class name:
class ScopeTest {
static int a = 5;
void printA() {
int a = 10;
System.out.println("The value of INSTANCE VARIABLE " +
"a is now: "+ScopeTest.a);
}
}
For now, it is best to stick to clear, unambiguous naming; you will return to
learn about the keyword this in-depth in a later chapter.
Search WWH ::




Custom Search