Java Reference
In-Depth Information
}
protected Port createSerialPort() {
return new EnhancedSerialPort();
}
}
Now when a HighSpeedPrinter is constructed and the initializers in Printer
execute, we invoke the overriding createSerialPort method that returns
an instance of EnhancedSerialPort .
This is one example of a situation in which a method of the subclass
is invoked before the subclass object has been fully constructed and so
care must be taken to ensure that things work correctly. For example,
if EnhancedSerialPort initializes a field using a field from the enclosing
HighSpeedPrinter instance, then at the time the EnhancedSerialPort object
is constructed, the fields of the enclosing object will have the default
"zero" values for their type.
An alternative design would have the constructor for HighSpeedPrinter
simply reassign serial to refer to an EnhancedSerialPort object. However,
that approach causes the unnecessary construction of the original Seri-
alPort object, and that construction may be non-trivial and undesirablein
this example it may involve configuring hardware.
 
Search WWH ::




Custom Search