Scope (or lexical scope) refers to the particular section
of code where a data field is visible and can be used.
Local scope
The scope for local variables is only within a method
or a block defined by the braces {} of a compound statement.
In this example,
public
double calc (double [] x, int n)
{
double sum = 0;
for( int i=0; i < n; i++) {
sum += x[i];
}
int i=10;
double val = Math.pow (sum, i);
return val;
} |
the variables include:
- x
- local variable that holds an array reference passed from the
method that invoked the
calc() method.
- n
- local variable that holds a copy of an integer value passed
from the method that invoked the
calc() method.
- sum
- local variable used in the summation.
- i
- in the loop this variable is valid only in the for
statement and its sub-expressions and between the loop braces;
that is, only in the for loop block.
- i
- when the loop finishes, the first i
disappears so another can be declared and used.
- val
- local variable, a copy of the value of which is returned.
When the method finishes, so do the local variables; their values
are not saved. They are temporary. The next time the method is
invoked, the local variables will be re-initialized.
Note that if the declaration
int
i = 10;
occurred before the loop, the compiler will complain about the
declaration of i in the for statement. The error will say that
the variable i
has already been defined.
Class scope
In this example,
public
class Test
{
double fRVal = 3.0;
public
double calc (double [] x, int n) {
double sum = 0;
for (int i=0; i < n; i++) {
sum += x[i];
}
int i = 10;
double val = Math.pow (sum, i);
return fRVal * val;
}
public
void setVal (double y)
{ fRVal = y;}
public double getVal ()
{ return fRVal;}
}
|
The instance variable fRval
has class scope. That is, it is accessible in all the methods
in the class. Instance variables like fRval
will last as long as the instance of
Test lasts.
Note that the Chapter
5: Java: Access Rules discusses optional restrictions on the
visibility of instance and static variables to subclasses.
Latest update: Oct. 25, 2004
|