Java Inner Classes Design Benefits
Inner classes are good when they are not used outside the containing class - it's a way of curtailing class bloat. As a general rule, that's the only time I use them.
Non-static inner classes also have access to the containing instance's private fields.
One good usage of inner classes that comes into my mind is in java.util.ArrayList that hides its iterators implementations into private inner classes
. You can't create them except by invoking iterator()
or listIterator()
on the list object.
This way the Iterator
and ListIterator
implementations for ArrayList
are grouped with their related class and methods for enhanced readability (the implementations are pretty short), but hidden from others.
They can't be declared static
as they need access to their enclosing instance object.
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
...
public Iterator<E> iterator() {
return new Itr();
}
private class Itr implements Iterator<E> {
...
}
public ListIterator<E> listIterator() {
return new ListItr(0);
}
private class ListItr extends Itr implements ListIterator<E> {
...
}
}