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 Objectthe only constructor
that can ever be used when an anonymous 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
becomes illegible. When anonymous classes are used properly, they are a good tool for keeping simple classes
simple. When misused, they create impenetrable inscrutability.
5.5. Inheriting Nested Types
Nested types, whether static classes, interfaces, or inner classes, are inherited the same way that fields are
inherited. A declaration of a nested type with the same name as that of an inherited nested type hides the
definition of the inherited type. The actual type referred to is determined by the type of the reference used.
Within a given class, the actual nested type referred to is the one defined in the current class or inherited in the
current class.
Consider a framework that models devices that can be connected by different ports. The class Device is an
abstract class that captures some common behavior of all devices. A port also has some common generic
behavior so it is also modeled as an abstract class and, because ports exist only within devices, the Port class
is made an inner class of Device. A concrete device class defines the state for the device and the concrete
inner port classes for that device. During construction of a concrete device class, references to the concrete
ports of that class are initialized:
abstract class Device {
abstract class Port {
// ...
}
// ...
}
class Printer extends Device {
class SerialPort extends Port {
// ...
}
Port serial = new SerialPort();
}
A concrete device can itself be extended, as can the concrete inner port classes, to specialize their behavior.
class HighSpeedPrinter extends Printer {
class SerialPort extends Printer.SerialPort {
// ...
}