loop counter), but the compiler has to be able to determine what each name meansand so does any human
being reading the code.
Name management is achieved with two mechanisms. First, the namespace is partitioned to give different
namespaces for different kinds of names. Second, scoping is used to control the visibility of names declared in
one part of a program to other parts. Different namespaces allow you to give the same name to a method and a
field (not that we recommend doing this), and scoping allows you to use the same name for all your for loop
counters.
There are six different namespaces:
- package names,
- type names,
- field names,
- method names,
- local variable names (including parameters), and
- labels
When a name is used in a program, its context helps determine what kind of name it is. For example, in the
expression x.f= 3 , we know that f must be a fieldit can't be a package, type, method, or label because we
are assigning a value to it, and it can't be a local variable because we are accessing it as a member of x. We
know that x must be a typename, or a field, or a local variable that is an object referenceexactly which one is
determined by searching the enclosing scope for an appropriate declaration, as you will see.
The use of separate namespaces gives you greater flexibility when writing code (especially when combining
code from different sources) but can be abused. Consider this pathological, but perfectly valid, piece of code:
package Reuse;
class Reuse {
Reuse Reuse(Reuse Reuse) {
Reuse:
for (;;) {
if (Reuse.Reuse(Reuse) == Reuse)
break Reuse;
}
return Reuse;
}
}
Every declaration of a name has a scope in which that name can be used. The exact rules differ depending on
the kind of nametype name, member name, local variable, and so on. For example, the scope of a parameter in
a method is the entire body of that method; the scope of a local variable is the block in which the local
variable is declared; the scope of a loop variable declared in the initialization section of a for loop is the rest
of that for loop.
A name cannot be used outside its scopefor example, one method in a class cannot refer to the parameter of
another method. However, scopes also nest and an inner scope has access to all names declared in the outer
scope before the inner scope is entered. For example, the body of a for loop can access the local variables of
the method in which it was declared.
When a name that could be a variable is used, the meaning of the name is determined by searching the current
and enclosing scopes for declarations of that name in the different namespaces. The search order is:
- Local variables declared in the code block, for loop, or as parameters to the catch clause of a try