Java Reference
In-Depth Information
Shape
instance stored in an array. When
Shape
's
draw()
method is called for an
arrayinstance,itisthe
Circle
's,
Rectangle
'sorother
Shape
instance's
draw()
methodthatgetscalled.Wesaythattherearemanyformsof
Shape
's
draw()
method,
or that this method is polymorphic.
Java supports four kinds of polymorphism:
•
Coercion
:Anoperationservesmultipletypesthroughimplicittypeconversion.
Forexample,divisionletsyoudivideanintegerbyanotherinteger,ordividea
floating-pointvaluebyanotherfloating-pointvalue.Ifoneoperandisaninteger
andtheotheroperandisafloating-pointvalue,thecompiler
coerces
(implicitly
converts)theintegertoafloating-pointvalue,topreventatypeerror.(Thereis
nodivisionoperationthatsupportsanintegeroperandandafloating-pointoper-
and.)Passingasubclassobjectreferencetoamethod'ssuperclassparameteris
anotherexampleofcoercionpolymorphism.Thecompilercoercesthesubclass
type to the superclass type, to restrict operations to those of the superclass.
•
Overloading
:Thesameoperatorsymbolormethodnamecanbeusedindiffer-
entcontexts.Forexample,
+
canbeusedtoperformintegeraddition,floating-
pointaddition,orstringconcatenation,dependingonthetypesofitsoperands.
Also, multiple methods having the same name can appear in a class (through
declaration and/or inheritance).
•
Parametric
:Withinaclassdeclaration,afieldnamecanassociatewithdifferent
types and a method name can associate with different parameter and return
types. The field and method can then take on different types in each class in-
stance. For example, a field might be of type
java.lang.Integer
and a
methodmightreturnan
Integer
referenceinoneclassinstance,andthesame
field might be of type
String
and the same method might return a
String
referenceinanotherclassinstance.Javasupportsparametricpolymorphismvia
•
Subtype
:Atypecanserveasanothertype'ssubtype.Whenasubtypeinstance
appearsinasupertypecontext,executingasupertypeoperationonthesubtype
instance results in the subtype's version of that operation executing. For ex-
ample, suppose that
Circle
is a subclass of
Point
, and that both classes
contain a
draw()
method. Assigning a
Circle
instance to a variable of
type
Point
,andthencallingthe
draw()
methodviathisvariable,resultsin
Circle
's
draw()
methodbeingcalled.Subtypepolymorphismpartnerswith
implementation inheritance.
Many developers do not regard coercion and overloading as valid kinds of poly-
morphism. They see coercion and overloading as nothing more than type conversions