Java Reference
In-Depth Information
Rules for local classes
A local class is an inner class. Therefore, it must satisfy all the rules for an
inner class. In addition, any local variable and parameter that it references must
be declared final so they cannot be changed after its initialization. Below, we
state the restrictions on a local class that is defined within another class. In the
class shown in Fig. 12.22, we have made inner class In public just in order to
give the rules most easily. Generally, inner classes would be made private.
Refer to Fig. 12.22 when reading the following rules for local inner classes:
See also a foot-
note on lesson
page 12.7.
1. The parameters and local variables that In accesses must have modifier
final . In Fig. 12.22, In can access parameter p1 and local variable
local1 , but In cannot reference p2 and local local2 , since they are not
final . The example program shows how to access the value of a non-
final parameter or local variable —assign it to a final local variable.
2. The only static components that In may have are final static fields that
are initialized with expressions that contain only constants and literals.
3. Class In can access all the static components of class Out even if they are
import java.util.*;
public class Out {
/** = an Iterator over b 's elements in reverse */
public static Iterator revIt( final Object[] b) {
/** a (reverse) Iterator over b */
class ItOver implements Iterator {
/** b[0..n-1] remains to be enumerated */
int n= b.length;
/** = " there is another element to process "*/
public boolean hasNext()
{ return n > 0; }
/** = the next item of the iteration */
public Object next() {
n= n - 1;
return b[n];
/** remove is not implemented */
public void remove() {}
return new ItOver();
Program 12.21:
A local inner class
Search WWH ::

Custom Search