Java Reference
In-Depth Information
Anonymous inner classes cannot have explicit constructors declared be-
cause they have no name to give the constructor. If an anonymous in-
ner class is complex enough that it needs explicit constructors then it
should probably be a local inner class. In practice, many anonymous in-
ner classes need little or no initialization. In either case, an anonymous
inner class can have initializers and initialization blocks that can access
the values that would logically have been passed as a constructor ar-
gument. The only construction problem that remains is the need to in-
voke an explicit superclass constructor. To solve this problem the new
expression is written as if a superclass instance were being constructed,
and that constructor is invoked as the superclass constructor. For ex-
ample, the following anonymous subclass of Attr (see page 76 ) invokes
the single-argument Attr constructor and overrides setValue to print out
the new value each time it is changed:
Attr name = new Attr("Name") {
public Object setValue(Object nv) {
System.out.println("Name set to " + nv);
return super.setValue(nv);
}
};
In the Iterator example we invoked the no-arg superclass constructor
for Object the only constructor that can ever be used when an anonym-
ous inner class has an interface type.
Anonymous classes are simple and direct but can easily become very
hard to read. The further they nest, the harder they are to understand.
The nesting of the anonymous class code that will execute in the future
inside the method code that is executing now adds to the potential for
confusion. You should probably avoid anonymous classes that are longer
than about six lines, and you should use them in only the simplest of
expressions. We stretch this rule in the walkThrough example because the
sole purpose of the method is to return that object, but when a method
does more, anonymous classes must be kept quite small or the code be-
comes illegible. When anonymous classes are used properly, they are a
 
Search WWH ::




Custom Search