Java Reference
In-Depth Information
LoggingApptCalendar lapptc = new LoggingApptCalendar();
lapptc.addAppts(new Appt[] {new Appt(), new Appt(), new
If you also add a System.out.println(msg); method call to Logger 's
log(String msg) method,tooutputthismethod'sargumenttostandardoutput,you
will discover that log() outputs a total of six messages; each of the expected three
messages (one per Appt object) is duplicated.
When LoggingApptCalendar 's addAppts() method is called, it first calls
Logger.log() for each Appt instance in the appts array that is passed to ad-
dAppts() . This method then calls ApptCalendar 's addAppts() method via
super.addAppts(appts); .
ApptCalendar 's addAppts() methodcalls LoggingApptCalendar 'sover-
riding addAppt() method for each Appt instance in its appts array argument.
addAppt() executes Logger.log(appt.toString()); tologits appt argu-
ment's string representation, and you end up with three additional logged messages.
If you did not override the addAppts() method, this problem would go away.
However, the subclass would be tied to an implementation detail: ApptCalendar 's
addAppts() method calls addAppt() .
mented. (I previously stated that you do not have access to ApptCalendar 's source
code.) When a detail is not documented, it can change in a new version of the class.
Becauseabaseclasschangecanbreakasubclass,thisproblemisknownasthe fragile
base class problem .Arelatedcauseoffragilitythatalsohastodowithoverridingmeth-
ods occurs when new methods are added to a superclass in a subsequent release.
Forexample,supposeanewversionofthelibraryintroducesanew public void
addAppt(Appt appt, boolean unique) method into the ApptCalendar
class.Thismethodaddsthe appt instancetothecalendarwhen unique isfalse,and,
when unique istrue,itaddsthe appt instanceonlyifithasnotpreviouslybeenad-
Becausethismethodhasbeenaddedafterthe LoggingApptCalendar classwas
created, LoggingApptCalendar does not override the new addAppt() method
with a call to Logger.log() . As a result, Appt instances passed to the new ad-
dAppt() method are not logged.
Search WWH ::

Custom Search