Java Reference
In-Depth Information
5.4. Anonymous Inner Classes
When a local inner class seems too much for your needs, you can declare
anonymous classes
that extend a class or implement an interface. These
classes are defined at the same time they are instantiated with
new
. For
example, consider the
walkThrough
method. The class
Iter
is fairly light-
weight and is not needed outside the method. The name
Iter
doesn't add
much value to the codewhat is important is that it is an
Iterator
object.
The
walkThrough
method could use an anonymous inner class instead:
public static Iterator<Object>
walkThrough(final Object[] objs) {
return new Iterator<Object>() {
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();
}
};
}
Anonymous classes are defined in the
new
expression itself, as part of
a statement. The type specified to
new
is the supertype of the anonym-
ous class. Because
Iterator
is an interface, the anonymous class in
walkThrough
implicitly extends
Object
and implements
Iterator
. An an-
onymous class cannot have an explicit
extends
or
implements
clause, nor
can it have any modifiers, including annotations.