Programming and Problem Solving with Java

(やまだぃちぅ) #1
7.5 Scope of Access | 341

Constant declarations do not follow this rule because the compiler computes constant val-
ues at compile time. That is, the compiler searches through our code to find all the constant
declarations before it computes their values. As a consequence, it doesn’t require us to define
a constant before referring to it. The JVM isn’t able to search through Bytecode in the same way,
so it requires us to initialize variables before their use in initialization expressions.
To make life easier for human readers of your code, it’s good form to define constants
ahead of any references to them. Some programmers even make a point of writ-
ing all constant declarations before the variable declarations, just as a reminder
that constants are given their values first.


Shadowing The scope rule that says local identifiers block access to identifiers


with the same name in the enclosing class is calledshadowing.
In Java, the scope of a local identifier is the remainder of the block follwing the
point at which it is declared.The block includes all of the statements between the
{and}that contain the declaration. For example:


public classSomeClass
{
static intvar; // Class member var
static final intCONST = 5; // Class member CONST
staticLabel label1;
public static voidsomeMethod(int param)
{
int var = CONST;
final intCONST = 10;
var = param * CONST;
label1.setText("" + var);
}
}

In this example, the scope of the local declarations extends from the point that each one ap-
pears to the end of the block. Thus, in the first use of CONST, to initialize varas part of its dec-
laration, the initialization refers to the class version of CONST. The second use of CONST in the
expression assigned to var, refers to the local constant.


Using thisRefer to an Object from Within Itself Java provides a keyword,this, which can be used


within an object to refer to the object itself. With regard to their scope, formal parameters
are treated as local identifiers that are declared at the beginning of the method body. Their
scope thus includes the entire body of the method.
Here’s an example showing the use of thisto access instance fields from within a method
that defines local names that shadow access to those fields:


public classSomeClass
{
static intvar = –1; // Instance member var
static final intCONST = 5; // Class member CONST


Shadowing A scope rule spec-
ifying that a local identifier dec-
laration blocks access to an
identifier declared with the
same name outside of the block
containing the local declaration.

Scope of local variable varwhich
shadows the same identifier
declared as a class member

Scope of local constant CONST,
which shadows the same identifier
declared as a class member. { }

Free download pdf