SE450: Inner Classes: Local Inner Classes [12/22] Previous pageContentsNext page

Inner classes can be created in code blocks, such as method bodies. These classes are not members of the class, so they can't be private, protected, public, static or final. They have access to the final variables of the code block as well as other members of the class, static and not-static. (think scope as to why this is the case)

Consider the Iterator interface (we talked about it last week and will look at it again tonight).

public interface Iterator {
  public boolean hasNext();
  public Object next();
  public void remove();
}
This interface is a great candidate for a local inner class.
public static Iterator walthThrough(final Object[] objs) {

  // local inner class
  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++];
    }
  }

  return new Iter();
}

Previous pageContentsNext page