Java Reference
In-Depth Information
inasuperclass.Acompilererrorproducedinthemethodisnotfoundin
anyofthesuperclasses.
Polymorphism
Yousaw,inChapter13,thatitispossibletohavemethodswiththesame
nameaslongastheyhavedifferentparameterlists.Weusedthisfeatureto
implementseveralconstructorsinthesameclass.Thecompilerisableto
determinewhichmethodistobeusedbyobservingthesignature.
Theoperationofconnectingcodetoaparticularmethodiscalledthe
binding
.Bindingcantakeplacewhentheprogramcompiles(called
staticbinding
)orwhentheprogramexecutes(called
dynamicbind-
ing
).
Polymorphism,ontheotherhand,meansmanyforms.Twomethods
withthesamenamearepolymorphic.Overloadinggeneratesstaticpoly-
morphism,sincethemethodtobeusedcanbedeterminedatcompile
time(staticbinding).Constructorswithdifferentsignaturesareover-
loaded,andareboundstatically.
Ininheritance,twoormoremethodswiththesamesignaturecoexist
inaclasshierarchy.Notethatinthecaseofinheritanceitispossiblefor
twomethodswithidenticalsignaturestobelocatedinthesameclasshi-
erarchy.Thisisdifferentfromoverloading,inwhichthemethodswiththe
samenamemusthavedifferentsignatures.
WhenJavaselectsbetweentwoormoremethodswiththesamesigna-
ture,locatedinthesameclassinheritancestructure,wesaythatthese-
lectiontakesplaceby
overriding
.Overridingdiffersfromoverloading
sinceinoverridingthemethodlinkedtotheobjectisdependentonthe
positionofthemethodintheclasshierarchy.Considerthreeclasses
namedClassA,ClassB,andClassCandassumethattherearetwopoly-
morphicmethodsnamedMethodA()andMethodB().Theclassdiagramis
shownin
Figure16-1
,
onthenextpage.
Inrelationto
Figure16-1
,
severalcasesofpolymorphismshouldbe
noted. First, when a call is made to MethodA() which of the two polymor-
phic implementations is used depends on the object making the call, as
follows: