Java Reference
In-Depth Information
Variable Scope and Method Definitions
One thing you must know to use a variable is its scope.
Scope
is the part of a program in which a variable or another type of information exists,
making it possible to use the variable in statements and expressions. When the part defin-
ing the scope has completed execution, the variable ceases to exist.
When you declare a variable in Java, that variable always has a limited scope. A variable
with local scope, for example, can be used only inside the block in which it was defined.
Instance variables have a scope that extends to the entire class, so they can be used by
any of the instance methods within that class.
When you refer to a variable, Java checks for its definition outward, starting with the
innermost scope.
The innermost scope could be a block statement, such as the contents of a
while
loop.
The next scope could be the method in which the block is contained.
If the variable hasn't been found in the method, the class itself is checked.
Because of the way Java checks for the scope of a given variable, it is possible for you to
create a variable in a lower scope that hides (or replaces) the original value of that vari-
able and introduces subtle and confusing bugs into your code.
For example, consider the following Java application:
class ScopeTest {
int test = 10;
5
void printTest() {
int test = 20;
System.out.println(“Test: “ + test);
}
public static void main(String[] arguments) {
ScopeTest st = new ScopeTest();
st.printTest();
}
}
In this class, you have two variables with the same name,
test
. The first, an instance
variable, is initialized with the value
10
. The second is a local variable with the value
20
.
The local variable
test
within the
printTest()
method hides the instance variable
test
.
When the
printTest()
method is called from within the
main()
method, it displays that
test
equals
20
, even though there's a
test
instance variable that equals
10
. You can