This is copied from JPL (see comment below), I added import and main():
import java.util.*;
/**
* @From "The Java Programming Language" by Arnold, Gosling, Holmes
* (5.3. Local Inner Classes)
*/
public class LocalInnerClassAppl {
public static Iterator<Object> walkThrough(final Object[] objs) {
class Iter implements Iterator<Object> {
private int pos = 0;
@Override
public boolean hasNext() {
return (pos < objs.length);
}
@Override
public Object next() throws NoSuchElementException {
if (pos >= objs.length)
throw new NoSuchElementException();
return objs[pos++];
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
return new Iter();
}
public static void main(String[] args) {
Object[] objects = new Object[5];
Iterator<Object> iter = walkThrough(objects);
while (iter.hasNext())
System.out.println(iter.next());
}
}
My questions are:
When iter.hasNext() is called, how iter can know what objs means? It was not explicitly saved in the instance. From discussion method-local inner class cannot use variables declared within the method it looks like it was implicitly copied and saved in iter instance. Could you confirm and substantiate it? I failed to find a reference.
If the first is true (the final parameter was saved), is it considered a good programming practice to rely on such implicit saving? Sorry if it is in the Java specifications, then my second Q is irrelevant, but again - I did not find it.
The result is 5 null's, I left the elements of the array uninitialized.