not the rule. In Java, the two major scopes are those defined by a class and those defined by
a method. Even this distinction is somewhat artificial. However, since the class scope has
several unique properties and attributes that do not apply to the scope defined by a method,
this distinction makes some sense. Because of the differences, a discussion of class scope
(and variables declared within it) is deferred until Chapter 6, when classes are described.
For now, we will only examine the scopes defined by or within a method.
The scope defined by a method begins with its opening curly brace. However, if that
method has parameters, they too are included within the method's scope. Although this topic
will look more closely at parameters in Chapter 6, for the sake of this discussion, they work
the same as any other method variable.
As a general rule, variables declared inside a scope are not visible (that is, accessible) to
code that is defined outside that scope. Thus, when you declare a variable within a scope, you
are localizing that variable and protecting it from unauthorized access and/or modification.
Indeed, the scope rules provide the foundation for encapsulation.
Scopes can be nested. For example, each time you create a block of code, you are creating
a new, nested scope. When this occurs, the outer scope encloses the inner scope. This means
that objects declared in the outer scope will be visible to code within the inner scope. However,
the reverse is not true. Objects declared within the inner scope will not be visible outside it.
To understand the effect of nested scopes, consider the following program:
// Demonstrate block scope.
class Scope {
public static void main(String args[]) {
int x; // known to all code within main
x = 10;
if(x == 10) { // start new scope
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
}
}
As the comments indicate, the variable x is declared at the start of main( )'s scope and is
accessible to all subsequent code within main( ). Within the if block, y is declared. Since a
block defines a scope, y is only visible to other code within its block. This is why outside of
its block, the line y = 100; is commented out. If you remove the leading comment symbol, a
compile-time error will occur, because y is not visible outside of its block. Within the if block,
x can be used because code within a block (that is, a nested scope) has access to variables
declared by an enclosing scope.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home