Java Reference
In-Depth Information
new scope. A scope determines what objects are visible to other parts of your program. It
also determines the lifetime of those objects.
Some other computer languages define two general categories of scopes: global and loc-
al. Although supported by Java, these are not the best ways to categorize Java's scopes. The
most important scopes in Java are those defined by a class and those defined by a method.
A discussion of class scope (and variables declared within it) is deferred until later in this
book, when classes are described. For now, we will examine only 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.
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 modific-
ation. 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 creat-
ing 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:
Search WWH ::




Custom Search