[PDF] [PDF] Polymorphism

Poly- morphism occurs in Java through the difference between the declared static class of a variable and the actual dynamic class of the value the variable 



Previous PDF Next PDF





[PDF] An Introduction to Polymorphism in Java - College Board

In the example below polymorphism is demonstrated by the use of multiple add methods The computer differentiates among them by the method signatures (the  



[PDF] Chapter 13 Inheritance and Polymorphism

For example, in the vehicle domain we could implement a Vehicle superclass as follows Vehicle java 1 2 3 4 5 6 7



[PDF] Java - Polymorphism - Tutorialspoint

Polymorphism is the ability of an object to take on many forms Now, the Deer class is considered to be polymorphic since this has multiple inheritance Deer d = new Deer(); Animal a = d; Vegetarian v = d; Object o = d;



[PDF] Inheritance and Polymorphism - Fas Harvard - Harvard University

Example: our Taxi class can define its own toString method: public String Inheritance in the Java API The name for this feature of Java is polymorphism



[PDF] Polymorphism through the Java Interface

To understand polymorphism, take an example of a workday at Franklin, Beedle, and Associates Kim brought in pastries while everyone was chatting When



[PDF] Polymorphism

Poly- morphism occurs in Java through the difference between the declared static class of a variable and the actual dynamic class of the value the variable 



[PDF] Chapter 9: Polymorphism Lab Exercises

Polymorphism via Inheritance Another Firm java Author: Lewis/Loftus // // Demonstrates polymorphism via For example, create a list, print it, and search for



[PDF] Polymorphism

Polymorphism A deeper look into Lets have a look at some examples java lang Object contains methods that all classes inherit ○ These include: ○ clone 



[PDF] Object- Oriented Programming: Polymorphism - Pearsoncmgcom

Consider the following example of polymorphism Suppose we 10 7 8 Common Interfaces of the Java API performed due to Java's polymorphic capabilities



[PDF] POLYMORPHISM

In software, polymorphism refers to a method that has different implementations in different subclasses of a class hierarchy This allows you to create a subclass 

[PDF] polymorphism in java example javatpoint

[PDF] polymorphism java example stackoverflow

[PDF] polynesie 2016 maths es

[PDF] polynésie 2016 maths es corrigé

[PDF] polynésie juin 2016 maths corrigé es

[PDF] polynesie juin 2016 maths s

[PDF] polynôme caractéristique

[PDF] polynome et fraction rationnelle cours

[PDF] polynomial lens distortion model

[PDF] polynomial solution

[PDF] polynomials and conjugate roots

[PDF] polynomials class 9 worksheet pdf

[PDF] polyphemus pronunciation

[PDF] polypnée definition arabe

[PDF] polypnée définition larousse

Chapter12PolymorphismThe termpolymorphichas Greek ro ots and means roughly \many forms."(poly= many,morphos=form.MorphosisrelatedtotheGreekgo dMorphus,whocouldapp eartosleeping individuals in any form he wished and hence was truly p olymorphic.)In biology,ap olymorphic sp ecies is one, suchasHomo Sapiens, that is characterized by the o ccurrenceof dierent forms or color typ es in individual organisms or among organisms.In chemistry,a p olymorphic comp ound is one that can crystallize in at least two distinct forms, suchascarb on, which can crystallize b oth as graphite and as diamond.12.1VarietiesofPolymorphismIn ob ject-oriented languages, p olymorphism is a natural result of theis-arelationship and ofthe mechanisms of message passing, inheritance, and the concept of substitutability.One ofthe great strengths of the OOP approach is that these devices can b e combined in a varietyof ways, yielding a numb er of techniques for co de sharing and reuse.Purepolymorphismo ccurswhenasinglefunctioncanbeappliedtoargumentsofavarietyof typ es.In pure p olymorphism, there is one function(co de b o dy)and a numberof interpretations.The other extreme o ccurs when wehavea numb er of dierent functions(co de b o dies) all denoted by the same name{a situation known asoverloadingor sometimesad hocpolymorphism.Between these two extremes areoverridinganddeferred methods.

1

1Notethatthereislittleagreementregardingterminologyintheprogramminglanguagecommu-nity.In[Horowitz 1984 ],[Marcotty 1987 ],[MacLennan 1987 ],and[Pinson 1988 ]forexample,polymor-phismis dened in a manner roughly equivalent to what we are here callingoverloading.In [Sethi 1989 ]and[Meyer 1988a ]andinthefunctionalprogramminglanguagescommunity(suchas[Wikstrom 1987 ,Milner 1990 ]),theterm is reservedforwhatwearecallingpurepolymorphism.Otherauthorsusethetermforone,two,orallofthemechanisms describ edinthischapter.Twocomplete,buttechnicallydaunting, analyses are [Cardelli 1985 ] and [Danforth 1988 ].207

208CHAPTER 12.POLYMORPHISM12.2PolymorphicVariablesWith the exception of overloading, p olymorphism in ob ject-oriented languages is made p os-sibleonlybytheexistenceofpolymorphicvariablesandtheideaofsubstitutability.Ap olymorphic variable is one with many faces; that is, it can hold values of dierenttyp es.Polymorphic variables embody the principle of substitutability.In other words, while thereis an expected typ e for anyvariable the actual typ e can b e from anyvalue that is a subtyp eof the exp ected typ e.In dynamically b ound languages (such as Smalltalk), all variables are p otentially p olymorphic{anyvariable can hold values of anytyp e.In these languages the desired typ e is dened bya setofexp ectedb ehaviors.Forexample,analgorithm may make useof anarrayvalue,exp ectingthesubscriptingop erationstobedenedforacertainvariable;anytyp ethatdenes the appropriate behavior is suitable.Thus, the user could dene his or her own typ eof array (for example, a sparse array) and, if the array op erations were implemented usingthe same names, use this new typ e with an existing algorithm.In statically typ ed languages, suchasJava, the situation is slightly more complex.Poly-morphismo ccursinJavathroughthedierencebetweenthedeclared(static)classofavariable and the actual (dynamic) class of the value the variable contains.Agoodexampleofap olymorphicvariableisthearrayallPilesintheSolitaregamepresentedinChapter9.Thearraywas declared asmaintainingavalueoftyp eCardPile,but in fact it maintains values from each of the dierent sub classes of the parent class.Amessagepresentedtoavaluefromthisarray,suchasdisplayintheexampleco deshownb elow, executes the metho d asso ciated with the dynamic typ e of the variable and not thatof the static class.publicclassSolitaireextendsAppletf...staticCardPileallPiles[];..publicvoidpaint(Graphicsg)ffor(inti=0;i<13;i++)allPiles[i].display(g);g...g12.3OverloadingWesay a function name isoverloadedif there are two or more function b o dies asso ciatedwith it.Note that overloading is a necessary part of overriding, whichwe and will describ e

12.3.OVERLOADING209in the next section, but the two terms are not identical and overloading can o ccur withoutoverriding.In overloading, it is the functionnamethat is p olymorphic{it has many forms.Anotherwaytothinkofoverloading andp olymorphismisthatthereisasingleabstractfunctionthat takes various typ es of arguments; the actual co de executed dep ends on the argumentsgiven.The fact that the compiler can often determine the correct function at compile time(in a strongly typ ed language), and can therefore generate only a single co de sequence aresimply optimizations.12.3.1OverloadingMessagesinRealLifeIn Chapter 1 wesaw an example in whichoverloading o ccurred without overriding, whenIwanted to surprise my friend with

owers for her birthday.One p ossible solution was tosend the messagesendFlowersToto my lo cal orist; another was to give thesamemessage tomy wife.Both my

orist and my wife (an instance of classSp ouse)would have understo o dthe message, and b oth would have acted on it to pro duce a similar result.In a certain sense,I could have thoughtofsendFlowersToas b eing one functionundersto o d by b oth my wifeand my

orist, but eachwould have used a dierent algorithm to resp ond to my request.Note,inparticular,thattherewasnoinheritanceinvolved inthisexample.Therstcommon sup erclass for my wife and my

orist was the categoryHuman.But certainly theb ehaviorsendFlowersTowas not asso ciated with all humans.My dentist, for example, whois also a human, would not have understo o d the message at all.12.3.2OverloadingandCo ercionAs an example more closely tied to programming languages, supp ose a programmer is devel-oping a library of classes representing common data structures.Anumb er of data structurescan b e used to maintain a collection of elements (sets, bags, dictionaries, arrays, and priorityqueues, for example), and these might all dene a metho d,add, to insert a new elementintothe collection.This situation{in whichtwo totally separate functions are used to provide semanticallysimilar actions for dierent data typ es{o ccurs frequently in all programming languages, notsimply in ob ject-oriented languages.Perhaps the most common example is the overloadingof the addition op erator, +.The co de generated by a compiler for an integer addition is oftenradically dierent from theco de generated for a

oating-p oint addition, yet programmerstend to think of the op erations as a single entity, the \addition" function.In this example it is imp ortant to p oint out that overloading may not b e the only activitytakingplace.Asemanticallyseparate op eration,coercion,isalso usuallyasso ciated witharithmetic op erations.It o ccurs when a value of one typ e is converted into one of a dierenttyp e.If mixed-typ e arithmetic is p ermitted, the addition of twovalues maybe interpretedin a numb er of dierentways:

210CHAPTER 12.POLYMORPHISMThere may b e four dierent functions, corresp onding to integer + integer, integer +real, real + integer, and real + real.In this case, there is overloading but no co ercion.There maybe two dierent functions for integer + integer and real + real.In integer+ real andreal + integer,theinteger valueis coerced by b eingchanged into a realvalue.In this situation there is a combination of overloading and co ercion.There may b e only one function, for real + real addition.All arguments are coercedinto b eing real.In this case there is co ercion only, with no overloading.12.3.3OverloadingfromSeparateClassesTherearetwodierentformsofoverloading thatcanbedistinguished.Oneformoccurswhen the same function name is found in two or more classes that are not linked by inher-itance.A second form o ccurs when two or more functions with the same name are foundwithin one class denition.The latter form will b e describ ed in the next section.Agoodexampleofoverloading ofthersttyp eisthemetho disEmpty.Thismetho dis used to determine if an ob ject is empty,however the exact meaning of empty will dierdep ending up on circumstances.The message is understo o d by the classesVector,HashtableandRectangle.The rst two are collection classes, and the message returns true when thereare no elements in the collection.In the classRectanglethe message returns true if eitherthe height or width of a rectangle is zero, and thus the rectangle has no area.Rectangler1=newRectangle();if(r1.isEmpty())...Overloading Do es Not Imply SimilarityThereisnothingintrinsictooverloadingthatrequiresthefunctionsasso ciatedwithanoverloaded nametohaveanysemanticsimilarity.Consideraprogramthatplaysacardgame, such as the solitaire game we examined in Chapter 9.The metho ddrawwas used todraw the image of a card on the screen.In another application we might also have includedadrawmetho d for the pack of cards, that is, to draw a single card from the top of the deck.Thisdrawmetho disnotevenremotelysimilarinsemanticstothedrawmetho dforthesingle card, and yet they share the same name.Note that this overloading of a single name withindep endent and unrelated meaningsshouldnotnecessarily be considered bad style, and generally it will not contribute to con-fusion.In fact, the selection of short, clear, and meaningful names suchasadd,draw, andso on, contributes to ease of understanding and correct use of ob ject-oriented comp onents.It is far simpler to rememb er that you canaddan element to a set than to recall that todo so requires invoking theaddNewElementmetho d,or, worse, that it requires calling theroutineSet

Mo duleAdditionMetho d.

12.4.OVERRIDING211All ob ject-oriented languages p ermitthe o ccurrence of metho ds with similar names inunrelated classes.In this case the resolution of overloaded names is determined by obser-vation of theclass of thereceiver for themessage.Nevertheless, thisdo es notmean thatfunctionsor metho dscan b ewrittenthat take arbitrary arguments.The statically typ ednature of Java still requires sp ecic declarations of all names.12.3.4ParametericOverloadingAnotherstyleofoverloading,inwhichpro cedures(orfunctionsormetho ds)inthesamecontextareallowedtoshareanameandaredisambiguatedbythenumberandtyp eofarguments supplied, is calledparametericoverloading;it o ccurs in Javaaswell as in someimp erative languages (such as Ada) and many functional languages.Parameteric overload-ingismostoftenfoundinconstructorfunctions.AnewRectangle,forexample,canbecreated either with no arguments (generating a rectangle with size zero and northwest cor-ner0,0),withtwointegerarguments(awidthandheight),withfourintegerarguments(width, height, northwest corner), with aPoint(the northwest corner, size is zero), with aDimension(height and width, corner 0,0), or with b oth aPointand aDimension.Rectangler1=newRectangle();Rectangler2=newRectangle(6,7);Rectangler3=newRectangle(10,10,6,7);Pointp1=newPoint(10,10);Dimensiond1=newDimension(6,7);Rectangler4=newRectangle(p1);Rectangler5=newRectangle(d1);Rectangler6=newRectangle(p1,d1);There are six dierent constructor functions in this class, all with the same name.Thecompilerdecideswhichfunctiontoexecutebasedonthenumberandtyp eofargumentsused with the function call.Overloadingisanecessaryprerequisitetotheotherformsofp olymorphismwewillconsider:overriding, deferred metho ds,and pure p olymorphism.Itis also often usefulinreducing the\conceptual space,"thatis,inreducingtheamountofinformation thattheprogrammer must rememb er.Often, this reduction in programmer-memory space is just assignicant as the reduction in computer-memory space p ermitted by co de sharing.12.4OverridingIn Chapter 8 we describ ed the mechanics of overriding, so it is not necessary to rep eat thatdiscussion here.Recall, however, the following essential elements of the technique.In oneclass (typically an abstract sup erclass), there is a general metho d dened for a particular

212CHAPTER12.POLYMORPHISMmessage that is inherited and used by sub classes.In at least one sub class, however, a metho dwith the same name is dened, that hides access to the general metho d for instances of thisclass (or,inthecase ofrenement,subsumes access tothegeneral metho d).Wesay thesecond metho doverridesthe rst.Overriding is often transparent to the user of a class, and, as with overloading, frequentlythe two functions are thought of semantically as a single entity.12.4.1ReplacementandRenementIn Chapter 9 we brie

y noted that overriding can o ccur in two dierent forms.A metho dcanreplacethemetho dintheparentclass,inwhichcasetheco deintheparentisnotexecutedat all.Alternatively,theco de fromthechildcan b eusedto formarenement,which combines the co de from the parent and the child classes.Normally,overridden metho ds use replacement semantics.If a renement is desired, itcan b e constructed by explicitly invoking the parent metho d as a function.This is accom-plished by using the pseudo-variablesup eras the receiver in a message passing expression.An example from the Solitare program describ ed in Chapter 9 showed this:classDiscardPileextendsCardPilefpublicvoidaddCard(CardaCard)fif(!aCard.faceUp())aCard.flip();super.addCard(aCard);ggConstructors, on the other hand,alwaysuse renement semantics.A constructor for achild class will always invoke the constructor for the parent class.This invo cation will takeplacebeforethe co de for the constructor is executed.If the constructor for the parent classrequires arguments, the pseudo-variablesup eris used as if it were a function:classDeckPileextendsCardPilefDeckPile(intx,inty)f//rstinitializeparentsuper(x,y);//thencreatethenewdeck//rstputthemintoalo calpilefor(inti=0;i<4;i++)for(intj=0;j<=12;j++)

12.5.ABSTRACT METHODS213addCard(newCard(i,j));//thenshuethecardsRandomgenerator=newRandom();for(inti=0;i<52;i++)fintj=Math.abs(generator.nextInt())%52;//swapthetwocardvaluesObjecttemp=thePile.elementAt(i);thePile.setElementAt(thePile.elementAt(j),i);thePile.setElementAt(temp,j);gggWhen used in this fashion, the call on the parent constructor must b e the rst statementexecuted.Ifnocallonsup erismakeexplicitlyandthereexisttwoormoreoverloadedforms of the constructor, the constructor with no arguments (sometimes called thedefaultconstructor) will b e the form used.12.5AbstractMetho dsA metho d that is declared asabstractcan b e thought of as dening a metho d that isdeferred;it is sp ecied in the parent class but must b e implemented in the child class.Interfaces canalsobeviewedasametho dfordeningdeferredclasses.Bothcanbeconsideredtobeageneralizationofoverriding.Inb othcases,theb ehaviordescrib edinaparentclassismo diedbythechildclass.Inanabstractmetho d,however,theb ehaviorintheparentclass is essentially null, a place holder, andal luseful activity is dened as part of the co deprovided by the child class.One advantage of abstract metho ds is conceptual, in that their use allows the program-mertothinkofanactivityasasso ciatedwithanabstraction atahigherlevelthanmayactually b e the case.For example, in a collection of classes representing geometric shap es,wecandeneametho dtodrawtheshap eineachofthesub classesCircle,Square,andTriangle.Wecouldhavedenedasimilarmetho dintheparentclassShap e,butsuchametho dcannot,inactuality,pro duceanyusefulb ehaviorsincetheclassShap edo esnothave sucient information to draw the shap e in question.Nevertheless, the mere presenceof this metho d p ermits the user to asso ciate the conceptdrawwith the single classShap e,and not with the three separate conceptsSquare,Triangle, andCircle.There is a second, more practical reason for using abstract metho ds.In statically typ edob ject-oriented languages, suchasJava, a programmer is p ermittedto send a message toan ob ject only if the compiler can determine that there is in fact a corresp onding metho d

214CHAPTER12.POLYMORPHISMthat matches the message selector.Supp ose the programmer wishes to dene a p olymorphicvariable of classShap ethat will, at various times, contain instances of each of the dierentshap es.Such an assignment is p ossible, according to our rule of substitutability; neverthe-less, the compiler will p ermit the messagedrawto b e used with this variable only if it canensure that the message will b e understo o d byanyvalue that may b e asso ciated with thevariable.Assigningametho dtotheclassShap eeectivelyprovidesthisassurance,evenwhen the metho d in classShap eis never actually executed.12.6PurePolymorphismMany authors reserve the termpolymorphism(orpurepolymorphism) for situations whereone functioncan b eusedwithavarietyofarguments,andthetermoverloading for situ-ationswheretherearemultiplefunctionsalldenedwithasinglename.

2Suchfacilitiesare notrestrictedtoob ject-oriented languages.InLispor ML,for example,itiseasy towrite functions that manipulate lists of arbitrary elements; such functions are p olymorphic,b ecause the typ e of the argument is not known at the time the function is dened.The abil-ity to form p olymorphic functions is one of the most p owerful techniques in ob ject-orientedprogramming.It p ermits co de to b e written once, at a high level of abstraction, and to b etailored as necessary totavariety of situations.Usually,theprogrammer accomplishesthis tailoring by sending further messages to the receiver for the metho d.These subsequentmessages oftenarenotasso ciated withtheclassatthelevelofthep olymorphicmetho d,but rather are deferred metho ds dened in the lower classes.An example will help us to illustrate this concept.As we noted in Chapter 8, the classNumb erisan abstractclass,parenttothewrapp er classes suchasInteger,Double,Float.The denition of the class is similar to the following:publicabstractclassNumberfpublicabstractintintValue();publicabstractlonglongValue();publicabstractfloatfloatValue();publicabstractdoubledoubleValue();

2The extreme cases may b e easy to recognize, but discovering the line that separates overloading fromp olymorphism can b e dicult. In b oth Java and ML a programmer can dene a numb er of functions, eachhaving the same name, but which take dierent arguments.Is it overloading in Java b ecause the variousfunctions sharing the same name are not dened in one lo cation, whereas in ML-style p olymorphism theymust all b e bundled together under a single heading?

12.7.EFFICIENCY AND POLYMORPHISM215publicbytebyteValue()freturn(byte)intValue();gpublicshortshortValue()freturn(short)intValue();ggThe metho dintValueis abstract and deferred{eachtyp e of number must provide theirownimplementationofthismetho d.Themetho dbyteValue,ontheotherhand,isnotoverridden.It is a purely p olymorphic algorithm.Regardless of whether the receiver is aninteger, a double precision

oating p ointvalue,or some other typeofnumb er,thisis theonly denition that will b e found.For all of these dierenttyp es, whenbyteValueis invokedthis will b e the algorithm that is executed.The imp ortant dening characteristic of pure p olymorphism, as opp osed to overloadingandoverriding,isthatthereisonefunctionwiththegivenname,usedwithavarietyofdierent arguments.Almost always, as in this case, the b o dy of such an algorithm will makeuse of other forms of p olymorphism, such as the invo cation of abstract functions shown here.12.7EciencyandPolymorphismAn essential p oint to note is that programming always involves compromises.In particular,programming withp olymorphism involves compromises b etweenease of development anduse,readability,andeciency.Inlargepart,eciencyhasb eenalreadyconsideredanddismissed; however, it would b e remiss not to admit that it is an issue, however slight.Afunction,suchasthebyteValuemetho ddescrib edinthelastsection,thatdo esnotknowthetyp eofitsargumentscanseldombeasecientasafunctionthathasmorecompleteinformation.Nevertheless,theadvantagesofrapiddevelopmentandconsistentapplication b ehavior and the p ossibilities of co de reuse usually more than make up for anysmall losses in eciency.12.8ChapterSummaryPolymorphism is an umbrella term that is used to describ e a variety of dierent mechanismsfound in programming languages.In ob ject-oriented languages the most imp ortant forms ofp olymorphism are tied to the p olymorphic variable{a variable that can hold many dierenttyp es of values.For example, overloading o ccurs when two or more functions share the samename.If these functions happ en to b e found in classes that have a parent class/child classrelationship, then it is called overriding. If an overridden function is used with a p olymorphicvariable, then the particular function executed will b e determined by the run-time value ofthe variable, not the compile-time declaration for the variable.

216CHAPTER 12.POLYMORPHISMOther forms of p olymorphism include overloading from indep endent classes, parametericoverloading (overloading that is disambiguated by the typ es of arguments used in a functioncall), and abstract methods.Notethattheuseofp olymorphismtendstooptimizeprogram developmenttimeandreliability, at the cost of run-time eciency.For most programs, the b enets far exceed thecosts.FurtherReadingIn the interests of completeness, it should b e mentioned that there is at least one importantstyleofp olymorphism,foundinothercomputerlanguages,thatisnotfoundinJava.Ageneric(sometimescalledatemplate)isatechniquethatallows aclass descriptiontobeparameterized with a typ e.In C++, for example, one could declare a class as follows:templateclassboxfpublic:box(Tinit)fvalue=initial;gTgetValue()freturnvalue;gprivateTvalue;g;The result is a \b ox of T", and not simply a b ox.To create suchavalue, one must alsosp ecify a typ e for the parameter value T:boxaBox(5);//createaboxwithanintegerboxaBox(Circle);//createaboxwithacircleOneimp ortantplacewherethismechanismisusefulisinthecreationofcollectionclasses (see Chapter 19).A language with generics, for example, would allow one to declareavectorof Cards, rather than (as in Java) simply a vector of ob jects.The compiler can thenverify that the collection contains only the indicated typ e of values.More imp ortantly, thecompiler can avoid the cast necessary in Java when an ob ject is removed from a containerA discussion of generics in relation to other forms of p olymorphism can b e found in [Budd 97].StudyQuestions1.What do es the term p olymorphic mean in common usage?2.What is a p olymorphic variable?

EXERCISES2173.Howisthecharacterization ofp olymorphicvariables dierentindynamicallytyp edlanguages than in staticly typ ed languages?4.What do es it mean to say that a function name is overloaded?5.What do es it mean to say that a value has b een co erced to a dierenttyp e?6.What is parameteric overloading?7.What is overriding, and how is it dierent from overloading?8.Whatisthedierencebetweenoverridingusingreplacement,andoverridingusingrenement?9.What is the default semantics for overriding for metho ds?For constructors?10.What is an abstract metho d?11.How is an abstract metho d denoted?12.What characterizes pure p olymorphism?13.Why should a programmer not b e overly concerned with the loss of eciency due tothe use of p olymorphic programming techniques?Exercises

1.Describ ethevarioustyp esofp olymorphismfoundinthePinballgameapplicationpresented in Chapter 7.2.Describ e the various typ es of p olymorphism found in the Solitare application presentedin Chapter 9.

quotesdbs_dbs19.pdfusesText_25