Java Reference
In-Depth Information
subclassmethodsignatureandreturntype.Yoursubclassmethodnowoverridesthesu-
perclass method, and probably does not fulfill the superclass method's contract.
Thereisawaytomaketheseproblemsdisappear.Insteadofextendingthesuperclass,
createaprivatefieldinanewclass,andhavethisfieldreferenceaninstanceofthe“su-
perclass.”Thistaskdemonstratescompositionbecauseyouareforminga“has-a”rela-
tionship between the new class and the “superclass.”
Additionally, have each of the new class's instance methods call the corresponding
“superclass” method via the “superclass” instance that was saved in the private field,
andalsoreturnthecalledmethod'sreturnvalue.Thistaskisknownas forwarding ,and
the new methods are known as forwarding methods .
Listing 2-31 presents animproved LoggingApptCalendar class that usescom-
positionandforwardingtoforevereliminatethefragilebaseclassproblemandthead-
ditional problem of the unanticipated method overriding.
Listing 2-31. A composed logging appointment calendar class
public class LoggingApptCalendar
{
private ApptCalendar apptCal;
public LoggingApptCalendar(ApptCalendar apptCal)
{
this.apptCal = apptCal;
}
public void addAppt(Appt appt)
{
Logger.log(appt.toString());
apptCal.addAppt(appt);
}
public void addAppts(Appt[] appts)
{
for (int i = 0; i < appts.length; i++)
Logger.log(appts[i].toString());
apptCal.addAppts(appts);
}
}
 
Search WWH ::




Custom Search