THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

local variable or parameter could be invoked after the completion of the method in which the local class was
definedand hence the local variables and parameters no longer existthe value of those variables must be frozen
before the local class object is created. If needed, you can copy a non-final variable into a final one that is
subsequently accessed by the local inner class.


Consider the standard interface Iterator defined in the java.util package. This interface defines a way
to iterate through a group of objects. It is commonly used to provide access to the elements in a container
object but can be used for any general-purpose iteration:


package java.util;


public interface Iterator {
boolean hasNext();
E next() throws NoSuchElementException;
void remove() throws UnsupportedOperationException,
IllegalStateException;
}


The hasNext method returns true if next has more elements to return. The remove method removes
from the collection the last element returned by next. But remove is optional, which means an
implementation is allowed to throw UnsupportedOperationException. If remove is invoked before
next, or is invoked multiple times after a single call to next, then IllegalStateException is thrown.
NoSuchElementExceptionalso part of the java.util packageis thrown if next is invoked when
there are no more elements. See "Iteration" on page 571 for more details.


Here is a simple method that returns an Iterator to walk through an array of Object instances:


public static Iterator
walkThrough(final Object[] objs) {


class Iter implements Iterator {
private int pos = 0;
public boolean hasNext() {
return (pos < objs.length);
}
public Object next() throws NoSuchElementException {
if (pos >= objs.length)
throw new NoSuchElementException();
return objs[pos++];
}
public void remove() {
throw new UnsupportedOperationException();
}
}
return new Iter();
}


The Iter class is local to the walkThrough method; it is not a member of the enclosing class. Because
Iter is local to the method, it has access to all the final variables of the methodin particular the parameter
objs. It defines a pos field to keep track of where it is in the objs array. (This code assumes that
Iterator and NoSuchElementException are imported from java.util in the source that contains
walkThrough.)


Members of local inner classes can hide the local variables and parameters of the block they are declared in,
just as they can hide instance fields and methods. The rules discussed on page 140 apply in all cases. The only