Java Reference
In-Depth Information
tiondetailsofthe
ApptCalendar
class.Youcanaddnewmethodsto
ApptCalen-
dar
and they will not break
LoggingApptCalendar
.
class
,aclasswhoseinstanceswrapotherinstances.Each
LoggingApptCalendar
instance wraps an
ApptCalendar
instance.
LoggingApptCalendar
is also an
example of the
Decorator design pattern
, which is presented on page 175 of
Design
Patterns: Elements of Reusable Object-Oriented Software
by Erich Gamma, Richard
Helm, Ralph Johnson, and John Vlissides (Addison-Wesley, 1995; ISBN:
0201633612).
When should you extend a class and when should you use a wrapper class? Extend
aclasswhenan“is-a”relationshipexistsbetweenthesuperclassandthesubclass,and
eitheryouhavecontroloverthesuperclassorthesuperclasshasbeendesignedanddoc-
umented for class extension. Otherwise, use a wrapper class.
Whatdoes“designanddocumentforclassextension”mean?Designmeansprovide
protected
methodsthathookintotheclass'sinnerworkings(tosupportwritingef-
ficient subclasses), and ensure that constructors and the
clone()
method never call
overridable methods. Document means clearly state the impact of overriding methods.
Caution
Wrapper classes should not be used in a
callback framework
, an object
frameworkinwhichanobjectpassesitsownreferencetoanotherobject(via
this
)so
thatthelatterobjectcancalltheformerobject'smethodsatalatertime.This“calling
backtotheformerobject'smethod”isknownasa
callback
.Becausethewrappedob-
ject does not know of its wrapper class, it passes only its reference (via
this
), and
resulting callbacks do not involve the wrapper class's methods.
Changing Form
Some real-world entities can change their forms. For example, water (on Earth as op-
posed to interstellar space) is naturally a liquid, but it changes to a solid when frozen,
anditchangestoagaswhenheatedtoitsboilingpoint.Insectssuchasbutterfliesthat
undergo metamorphosis are another example.
The ability to change form is known as
polymorphism
, and is useful to model in a
programminglanguage.Forexample,codethatdrawsarbitraryshapescanbeexpressed
more concisely by introducing a single
Shape
class and its
draw()
method, and
by invoking that method for each
Circle
instance,
Rectangle
instance, and other