Java Reference
In-Depth Information
Scope of an Identifier Within a Class
The previous sections presented several examples of programs with user-defined methods.
In these examples, and in Java in general, identifiers are declared in a method heading,
within a block, or outside a block. (Recall that an identifier is the name of something in
Java, such as a variable or method.) A question naturally arises: Are you allowed to access
any identifier anywhere in the program? The general answer is no. Certain rules exist that
you must follow to access an identifier. The scope of an identifier refers to what parts of
the program can ''see'' an identifier, that is, where it is accessible (visible). This section
examines the scope of an identifier. Let's first define the following widely used term:
Local identifier: An identifier declared within a method or block that is visible only
within that method or block.
Before giving the scope rules of an identifier, let us note the following:
￿ Java does not allow the nesting of methods. That is, you cannot include
the definition of one method in the body of another method.
￿ Within a method or a block, an identifier must be declared before it can
be used. Note that a block is a collection of statements enclosed within
braces. A method's definition can contain several blocks. The body of a
loop or an if statement also forms a block.
￿ Within a class, outside every method definition (and every block), an
identifier can be declared anywhere.
￿ Within a method, an identifier used to name a variable in the outer block
of the method cannot be used to name any other variable in an inner
block of the method. For example, in the following method definition,
the second declaration of the variable x is illegal:
public static void illegalIdentifierDeclaration()
{
int x;
//block
{
double x;
//illegal declaration, x is already declared
...
}
}
Next, we describe the scope rules of an identifier declared within a class and accessed
within a method (block) of the class. (In Chapter 8, we describe the rules for an object to
access the identifiers of its class.)
￿
An identifier, say, x , declared within a method (block) is accessible:
￿ Only within the block from the point at which it is declared until the
end of the block.
￿ By those blocks that are nested within that block.
 
Search WWH ::




Custom Search