Java Reference
In-Depth Information
class HighSpeedPrinter extends Printer {
class SerialPort extends Printer.SerialPort {
// ...
}
}
The intent is that the class
HighSpeedPrinter.SerialPort
overrides the
class
Printer.SerialPort
so that
serial
is set to refer to the correct type
of object. But the class
Printer
is not affected by the new subclass of
SerialPort
defined inside
HighSpeedPrinter
, even though the new subclass
seems to have the same name.
One solution to this design problem is to abstract construction of the in-
ner class objects into a
factory method
which can then be overridden in
a subclass to construct the right kind of inner class. For example:
class Printer extends Device {
class SerialPort extends Port {
// ...
}
Port serial = createSerialPort();
protected Port createSerialPort() {
return new SerialPort();
}
}
The
HighSpeedPrinter
class now defines its specialized inner class and
overrides the factory method to construct an instance of that class. Now
that we realize that nested type definitions hide and don't override, we
aren't tempted to use the same name for the inner class, for we know
that hiding is usually a bad thing.
class HighSpeedPrinter extends Printer {
class EnhancedSerialPort extends SerialPort {
// ...