6.3 Scope of a Simple Name
The scope of a declaration is the region of the program within which the entity
declared by the declaration can be referred to using a simple name:
- The scope of a package, as introduced by a
package
declaration, is determined by the host system (§7.4.3). All Java code is within the scope of the standard package named java
, so the package java
can always be referred to by Java code.
- The scope of a type imported by a single-type-import declaration (§7.5.1) or type-import-on-demand declaration (§7.5.2) is all the class and interface type declarations (§7.6) in the compilation unit in which the import declaration appears.
- The scope of a type introduced by a class type declaration (§8.1.1) or interface type declaration (§9.1.1) is the declarations of all class and interface types in all the compilation units (§7.3) of the package in which it is declared.
- The scope of a member declared in or inherited by a class type (§8.2) or interface type (§9.2) is the entire declaration of the class or interface type. The declaration of a member needs to appear before it is used only when the use is in a field initialization expression (§8.3.2, §12.4.2, §12.5). This means that a compile-time error results from the test program:
class Test {
int i = j; // compile-time error: incorrect forward reference
int j = 1;
}
whereas the following example compiles without error:
class Test {
Test() { k = 2; }
int j = 1;
int i = j;
int k;
}
even though the constructor (§8.6) for Test
refers to the field k
that is declared three lines later.
- The scope of a parameter of a method (§8.4.1) is the entire body of the method.
- The scope of a parameter of a constructor (§8.6.1) is the entire body of the constructor.
- The scope of a local variable declaration in a block (§14.3.2) is the rest of the block in which the declaration appears, starting with its own initializer (§14.3) and including any further declarators to the right in the local variable declaration statement.
- The scope of a local variable declared in the ForInit part of a
for
statement (§14.12) includes all of the following:
- Its own initializer
- Any further declarators to the right in the ForInit part of the
for
statement
- The Expression and ForUpdate parts of the
for
statement
- The contained Statement
- The scope of a parameter of an exception handler that is declared in a
catch
clause of a try
statement (§14.18) is the entire block associated with the catch
.
These rules imply that declarations of class and interface types need not appear
before uses of the types.
In the example:
package points;
class Point {
int x, y;
PointList list;
Point next;
}
class PointList {
Point first;
}
the use of PointList
in class Point
is correct, because the scope of the class type
name PointList
includes both class Point
and class PointList
, as well as any
other type declarations in other compilation units of package points
.