Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^340) | Inheritance, Polymorphism, and Scope


Internal Scope


Any identifier declared as a staticor instance member of a class can be used anywhere
within the class, with two exceptions. You can’t use one class variable to initialize another
before the first one has been defined. And, within its block, a local identifier hides a class
member of the same name. Let’s take a closer look at each of these exceptions.

Order of Definition Suppose you are defining a Circleclass and you want to provide class vari-


ables that are initially set to pi and pi times two. The first of the following two declarations
is illegal because its initialization expression uses the second identifier before it has been
given a value:

public static doubletwoPI = PI * 2; // PI isn't defined yet
public static doublePI = 3.14159265358979323846;

Reversing the order of the statements makes them both legal:

public static doublePI = 3.14159265358979323846;
public static doubletwoPI = PI * 2; // PI already has a value

The scope rule that requires us to define a class variable’s value before it is used applies
only to references in expressions that initialize other class variables as part of their decla-
ration. Otherwise, it’s legal to refer to class variables before they are defined. For example,
the following declarations are legal:

public static intcircumference(Circle anyCircle)
{
returnanyCircle.radius * twoPI;
}
static doublePI = 3.14159265358979323846;
static doubletwoPI = PI * 2;

In this code, the method is allowed to refer to the variabletwoPIbefore it is defined. Why is
this case different? The JVM performs all class variable declaration initializations before it
starts executing statements inmain, and it does so in the order that the initializations are writ-
ten in the code. So an initialization expression can use only class variables that have already
been given values.
The method circumferenceisn’t executed until it is called from some point in the program,
which can happen only after all of the variable declaration initializations are complete. In
terms of the order of execution, all initialization expressions are executed before any other
use of a variable.
Note that regular assignment statements that initialize variables in methods are distinct
from declaration initialization expressions. They are executed in the normal flow of control,
which starts after all of the declaration initializations take place.

T


E


A


M


F


L


Y


Team-Fly®

Free download pdf