| OGT Home | UPF Home | View Cart |
CITATION
PDF VIEWER
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Full Citation | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
STANDARD VIEW
MARC VIEW
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Downloads | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Full Text | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
PAGE 1 PrinciplesofObject-OrientedProgramming CollectionEditors: StephenWong DungNguyen PAGE 3 PrinciplesofObject-OrientedProgramming CollectionEditors: StephenWong DungNguyen Authors: MarkHusband DungNguyen StephenWong Online: < http://cnx.org/content/col10213/1.31/ > CONNEXIONS RiceUniversity,Houston,Texas PAGE 4 2008StephenWong,DungNguyen ThisselectionandarrangementofcontentislicensedundertheCreativeCommonsAttributionLicense: http://creativecommons.org/licenses/by/1.0 PAGE 5 TableofContents 1Introduction 1.1 Abstraction.................................................................................1 1.2 ObjectsandClasses.........................................................................5 1.3 ObjectRelationships........................................................................9 1.4 UMLDiagrams.............................................................................12 Solutions........................................................................................ ?? 2PolymorphisminAction 2.1 UnionDesignPattern:InheritanceandPolymorphism......................................15 2.2 Ballworld,inheritance-based................................................................21 2.3 Ballworld,composition-based...............................................................27 Solutions........................................................................................35 3ImmutableListStructure 3.1 ListStructureandtheCompositeDesignPattern...........................................37 3.2 ListStructureandtheInterpreterDesignPattern...........................................41 3.3 VisitorDesignPattern......................................................................43 3.4 AbstractFactoryDesignPattern...........................................................55 3.5 InnerClasses...............................................................................64 Solutions........................................................................................ ?? 4MutableDataStructures 4.1 StateDesignPattern.......................................................................85 4.2 MutableLinearRecursiveStructure........................................................87 4.3 BinaryTreeStructure......................................................................93 4.4 ArraysandArrayProcessing...............................................................97 Solutions........................................................................................ ?? 5RestrictedAccessContainers 5.1 RestrictedAccessContainers..............................................................105 5.2 OrderingObjectandPriorityQueue.......................................................112 Solutions........................................................................................ ?? 6GUIProgramming 6.1 GraphicalUserInterfacesinJava..........................................................113 6.2 MoreJavaGUIProgramming.............................................................117 Solutions........................................................................................ ?? 7Labs 7.1 DrJava....................................................................................121 7.2 UnitTestingwithJUnitinDrJava........................................................123 Solutions........................................................................................ ?? 8Resources 8.1 JavaSyntaxPrimer.......................................................................131 8.2 Connexions................................................................................132 Solutions........................................................................................ ?? Glossary ............................................................................................137 Index ...............................................................................................143 Attributions ........................................................................................146 PAGE 6 iv PAGE 7 Chapter1 Introduction 1.1Abstraction 1 1.1.1Introduction Abstractionistheprocessofhidingthedetailsandexposingonlytheessentialfeaturesofaparticularconcept orobject.Computerscientistsuseabstractiontounderstandandsolveproblemsandcommunicatetheir solutionswiththecomputerinsomeparticularcomputerlanguage.Weillustratethisprocessbywayof tryingtosolvethefollowingproblemusingacomputerlanguagecalledJava. Problem :Givenarectangle4.5ftwideand7.2fthigh,computeitsarea. Weknowtheareaofarectangleisitswidthtimesitsheight.Soallwehavetodotosolvetheabove problemistomultiply4.5by7.2andgetthetheanswer.Thequestionishowtoexpresstheabovesolution inJava,sothatthecomputercanperformthecomputation. 1.1.2DataAbstraction Theproductof4.5by7.2isexpressedinJavaas: 4.5*7.2 .Inthisexpression,thesymbol represents themultiplicationoperation.4.5and7.2arecallednumber literals .UsingDrJava,wecantypeinthe expresssion 4.5*7.2 directlyintheinteractionswindowandseetheanswer. Nowsupposewechangetheproblemtocomputetheareaofarectangleofwidth3.6andheight9.3.Has theoriginalproblemreallychangeatall?Toputitinanotherway,hasthe essence oftheoriginalproblem changed?Afterall,theformulaforcomputingtheanswerisstillthesame.Allwehavetodoistoenter3.6 *9.3.Whatisitthathas not changethe invariant ?Andwhatisitthathaschangedthe variant ? 1.1.2.1TypeAbstraction Theproblemhasnotchangedinthatitstilldealswiththesamegeometricshape,arectangle,describedin termsofthesamedimensions,itswidthandheight.Whatvaryaresimplythevaluesofthewidthandthe height.Theformulatocomputetheareaofarectanglegivenitswidthandheightdoesnotchange: width*height Itdoesnotcarewhattheactualspecicvaluesofwidthandheightare.Whatitcaresaboutisthatthe valuesofwidthandheightmustbesuchthatthemultiplicationoperationmakessense.Howdoweexpress theaboveinvariantsinJava? Wejustwanttothinkofthewidthandheightofagivenrectangleaselementsofthesetofrealnumbers. Incomputing,wegroupvalueswithcommoncharacteristicsintoasetandcalledita type .InJava,the 1 Thiscontentisavailableonlineat PAGE 8 2 CHAPTER1.INTRODUCTION type double isthesetofrealnumbersthatareimplementedinsidethecomputerinsomespecicway.The detailsofthisinternalrepresentationisimmaterialforourpurposeandthuscanbeignored.Inaddition tothetypedouble,Javaprovidesmanymorepre-builttypessuchas int torepresentthesetofintegers and char torepresentthesetofcharacters.Wewillexamineandusethemastheirneedarisesinfuture examples.Astoourproblem,weonlyneedtorestrictourselvestothetypedouble. WecandenethewidthandtheheightofarectangleasdoubleinJavaasfollows. doublewidth; doubleheight; Theabovetwostatementsarecalled variable denitionswherewidthandheightaresaidtobevariable names.InJava,avariablerepresentsamemorylocationinsidethecomputer.Wedeneavariableby rstdeclareitstype,thenfollowthetypebythenameofthevariable,andterminatethedenitionwitha semi-colon.ThisaJavasyntaxrule.Violatingasyntaxruleconstitutesanerror.Whenwedeneavariable inthismanner,itsassociatedmemorycontentisinitializedtoadefaultvaluespeciedbytheJavalanguage. Forvariablesoftypedouble,thedefaultvalueis0. note: UsetheinteractionspaneofDrJavatoevaluatewidthandheightandverifythattheirvalues aresetto0. Oncewehavedenedthewidthandheightvariables,wecansolveourproblembywritingtheexpression thatcomputestheareaoftheassociatedrectangleintermsofwidthandheightasfollows. width*height Observethatthetwovariabledenitionstogetherwiththeexpressiontocomputetheareapresentedin theabovedirectlytranslatethedescriptionoftheproblem-tworealnumbersrepresentingthewidthandthe heightofarectangle-andthehigh-levelthinkingofwhatthesolutionoftheproblemshouldbe-areaisthe widthtimestheheight.Wehavejustexpressedtheinvariantsoftheproblemanditssolution.Now,howdo wevarywidthandheightinJava?Weusewhatiscalledthe assignment operation.Toassignthevalue 4.5tothevariablewidthandthevalue7.2tothevariableheight,wewritethefollowingJavaassignment statements. width=4.5; height=7.2; ThesyntaxrulefortheassignmentstatementinJavais:rstwritethenameofthevariable,thenfollow itbytheequalsign,thenfollowtheequalsignbyaJavaexpression,andterminateitwithasemi-colon. Thesemantici.e.meaningofsuchanassignmentis:evaluatetheexpressionontherighthandsideofthe equalsignandassigntheresultingvalueintothememorylocationrepresentedbythevariablenameonthe lefthandsideoftheequalside.Itisanerrorifthetypeoftheexpressionontherighthandsideisnot a subset ofthetypeofthevariableonthelefthandside. Nowifweevaluate width*height againusingtheInteractionsWindowofDrJava,weshouldget thedesiredanswer.Lifeisgoodsofar,thoughthereisalittlebitofinconveniencehere:wehavetotype theexpressionwidth*heighteachtimeweareaskedtocomputetheareaofarectanglewithagivenwidth andagivenheight.ThismaybeOKforsuchasimpleformula,butwhatiftheformulaissomethingmuch morecomplex,likecomputingthelengthofthediagonalofarectangle?Re-typingtheformulaeachtimeis quiteanerror-proneprocess.Isthereawaytohavethecomputermemorizetheformulaandperformthe computationbehindthescenesothatwedonothavetomemorizeitandrewriteitourselves?Theanswer isyes,andittakesalittlebitmoreworktoachievethisgoalinJava. Whatwewouldliketodoistobuildtheequivalentofablackboxthattakesinasinputstworealnumbers recalltype double withabutton.Whenweputintwonumbersanddepressthebutton,"magically"the blackboxwillcomputetheproductofthetwoinputnumbersandspitouttheresult,whichwewillinterpret PAGE 9 3 astheareaofarectanglewhosewidthandheightaregivenbythetwoinputnumbers.Thisblackboxisin essenceaspecializedcalculatorthatcanonlycomputeonething:theareaofarectanglegivenawidthand aheight.TobuildthisboxinJava,weuseaconstructcalledaclass,whichlookslikethefollowing. classAreaCalc{ doublerectangledoublewidth,doubleheight{ returnwidth*height; } } WhatthisJavacodemeansissomethinglike: AreaCalc isa blueprint ofaspecializedcomputingmachine thatiscapableofacceptingtwoinput doubles ,onelabeledwidthandtheotherlabeledheight,computing theirproductandreturningtheresult.Thiscomputationisgivenaname: rectangle .InJavaparlance,it iscalleda method fortheclass AreaCalc Hereisanexampleofhowweuse AreaCalc tocomputeareaofarectangleeofwidth4.5andheight7.2. IntheInteractionspaneofDrJava,enterthefollowinglinesofcode. AreaCalccalc=newAreaCalc; calc.rectangle.5,7.2 Therstlineofcodedenes calc asavariableoftype AreaCalc andassigntoitan instance oftheclass AreaCalc new isakeywordinJava.Itisanexampleofwhatiscalledaclassoperator.Itoperatesona classandcreatesaninstancealsocalled object ofthegivenclass.Thesecondlineofcodeisacalltothe object calc toperformthe rectangle taskwhere width isassignedthevalue4.5and height isassigned thevalue7.2.Togettheareaofa5.6by8.4rectangle,wesimplyusethesamecalculator calc again: calc.rectangle.6,8.4; Soinsteadofsolvingjustoneproble-givenarectangle4.5ftwideand7.2fthigh,computeitsarea-we havebuilta"machine"thatcancomputetheareaof any givenrectangle.Butwhataboutcomputingthe areaofarighttrianglewithheight5andbase4?Wecannotsimplyusethiscalculator.Weneedanother specializedcalculator,thekindthatcancomputetheareaofacircle. Thereareatleasttwodierentdesignsforsuchacalculator. createanewclasscalledAreaCalc2withonemethodcalled rightTriangle withtwoinputparametersoftype double .Thiscorrespondstodesigningadierentareacalculatorwithonebuttonlabeled rightTriangle withtwoinputslots. addtoAreaCalcamethodcalledrightTrianglewithtwoinputparametersoftype double .This correspondstodesigninganareacalculatorwithtwobuttons:onelabeled rectangle withtwoinput slotsandtheotherlabeled rightTriangle ,alsowithtwoinputslots. Ineitherdesign,itistheresponsibilityofthecalculatorusertopicktheappropriatecalculatororpressthe appropriatebuttononthecalculatortocorrectlyobtaintheareaofthegivengeometricshape.Sincethetwo computationsrequireexactlythesamenumberofinputparametersofexactlythesametype,thecalculator usermustbecarefulnotgetmixedup.Thismaynotbetoomuchofaninconvenienceifthereareonlytwo kindsofshapetochoosefrom:rectangleandrighttriangle.Butwhatiftheuserhastochoosefromhundreds ofdierentshapes?orbetteryetan open-ende numberofshapes?Howcanwe,asprogrammers,buida calculatorthatcanhandlean innite numberofshapes?Theanswerliesin abstraction .Tomotivatehow conceptualizetheproblem,letusdigressandcontemplatethebehaviorofachild! 1.1.2.2ModelingaPerson Fortherstfewyearsofhislife,Peterdidnothaveacluewhatbirthdayswere,letalonehisownbirth date.Hewasincapableofrespondingtoyourinquiryonhisbirthday.Itwashisparentswhoplannedfor PAGE 10 4 CHAPTER1.INTRODUCTION hiselaboratebirthdaypartiesmonthsinadvance.WecanthinkofPeterthenasarather"dumb"person withverylittleintelligenceandcapability.NowPeterisacollegestudent.Thereisapieceofmemoryinhis brainthatstoreshisbirthdate:it'sSeptember12,1985!Peterisnowarathersmartperson.Hecangure outhowmanymoremonthstillhisnextbirthdayande-mailhiswishlisttwomonthsbeforehisbirthday. Howdowemodela"smart"personlikePeter?Modelingsuchapersonentailsmodeling abirthdateand thecomputationofthenumberofmonthstillthenextbirthdaygiventhecurrentmonth. Abirthdateconsistsofamonth,adayandayear.Eachofthesedatacanberepresentedbyaninteger,which inJavaiscalledanumberoftype int .Asinthecomputationoftheareaofarectangle,thecomputation ofthenumberofmonthstillthenextbirthdaygiventhecurrentmonthcanberepresentedasamethod ofsomeclass.Whatwewilldointhiscasethatisdierentfromtheareacalculatoriswewilllumpboth thedatai.e.thebirthdateandthecomputationinvolvingthebirthdateintooneclass.Thegroupingof dataandcomputationsonthedataintooneclassiscalledencapsulation.BelowistheJavacodemodeling anintelligentpersonwhoknowshowtocalculatethenumberofmonthsbeforehis/hernextbirthday.The linenumbersshownarethereforeasyreferencingandarenotpartofthecode. 1publicclassPerson{ 2/** 3*Alldatafieldsareprivateinordertopreventcodeoutsideofthis 4*classtoaccessthem. 5*/ 6privateint_bDay;//birthday 7privateint_bMonth;//birthmonth;forexample,3meansMarch. 8privateint_bYear;//birthyear 9/** 10*Constructor:aspecialcodeusedtoinitializethefieldsoftheclass. 11*TheonlywaytoinstantiateaPersonobjectistocallnewontheconstructor. 12*Forexample:newPerson,2,1945willcreateaPersonobjectwith 13*birthdateFebruary28,1945. 14*/ 15publicPersonintday,intmonth,intyear{ 16_bDay=day; 17_bMonth=month; 18_bYear=year; 19} 20/** 21*Uses"modulo"arithmetictocomputethenumberofmonthstillthenext 22*birthdaygiventhecurrentmonth. 23*@paramcurrentMonthanintrepresentingthecurrentmonth. 24*/ 25publicintnMonthTillBDintcurrentMonth{ 26return_bMonth-currentMonth+12%12; 27} 28} Downloadtheabovecode 2 WenowexplainwhattheaboveJavacodemeans. 2 http://cnx.org/content/m11785/latest/Person.java PAGE 11 5 line1denesaclasscalledPerson.Theopeningcurlybraceattheendofthelineandthematching closingbraceonline28delimitthecontentsofclassPerson.Thekeyword public iscalledan access specier andmeansallJavacodeinthesystemcanreferencethisclass. lines2-5arecomments.Everythingbetween/*and*/areingoredbythecompiler. lines6-8denethreeintegervariables.Thesevariablesarecalled elds oftheclass.Thekeyword privateisanotheraccessspecierthatpreventsaccessbycodeoutsideoftheclass.Onlycodeinside oftheclasscanaccessthem.Eacheldisfollowedbyacommentdelimitedby//andtheend-of-line. SotheretwowaystocommentcodeinJava:startwith/*andendwith*/orstartwith//andend withtheend-of-line. lines9-14arecomments. lines15-19constitutewhatiscalleda constructor .Itisusedtoinitializetheeldsoftheclassto someparticularvalues.Thenameoftheconstructorshouldspellexactlyliketheclassname.Here itis public ,menaingitcanbecalledbycodeoutsideoftheclassPersonviatheoperatornew.For example, newPerson,2,1945 willcreateaninstanceofaPersonwith_bDay=28,_bMonth =2and_bYear=1945. lines20-24arecomments. line23isaspecialformatfordocumentingtheparametersofametod.Thisformatiscalledthejavadoc format.Wewilllearnmoreaboutjavadocinanothermodule. lines25-27constitutethedenitionofamethodinclassPerson. line26istheformulaforcomputingthenumberofmonthsbeforethenextbirthdayusingtheremainder operator%.x%ygivestheremainderoftheintegerdivisionbetweenthedividendxandthedivisor y. 1.2ObjectsandClasses 3 1.2.1Objects Inthe"real"world,objectsaretheentitiesofwhichtheworldiscomprised.Everythingthathappensin theworldisrelatedtotheinteractionsbetweentheobjectsintheworld.Justasatoms,whichareobjects, combinetoformmoleculesandlargerobjects,theinteractingentitiesintheworldcanbethoughtofas interactionsbetweenandamongbothsingular"atomic"aswellascompound"composed"objects.The realworldconsistsofmany,manyobjectsinteractinginmanyways.Whileeachobjectmaynotbeoverly complex,theirmyriadofinteractionscreatestheoverallcomplexityofthenaturalworld.Itisthiscomplexity thatwewishtocaptureinoursoftwaresystems. Inanobject-orientedsoftwaresystem, objects areentitiesusedtorepresentormodelaparticularpiece ofthesystem. Objectsaretheprimaryunitsusedtocreateabstractmodels. Thereareanumberofschoolsofobject-orientedprogramming,whichdierslightlyonhowtheyview objects.Here,wewilltakea"behaviorist"ourtermstance: Anobjectischaracterizedsolelybyitbehaviors. Essentiallythisdenesanobjectbythewayitinteractswithitsworld.Anobjectthatdoesnotinteract withanythingelseeectivelydoesnotexist.Accesstointernallystoreddataisnecessarilythroughsome sortofdenedbehavioroftheobject.Itisimpossibleforanoutsideentitytotruly"know"whetherornot aparticularpieceofdataisbeingstoredinsideofanotherobject. note: Abeautifulexampleofamodelthatexhibitsaparticularbehaviorbutwithoutexactly replicatingthemechanicsweexpecttoproducethatbehavioristhe"Dragon"opticalillusion.A 3 Thiscontentisavailableonlineat PAGE 12 6 CHAPTER1.INTRODUCTION printouttocreatethissimplefoldedpaperdisplaycanbefoundatthewebsiteoftheGrand IllusionsToyShopinEngland 4 Thisdoesnotmeanhowever,thatanobjectmaynotcontaindatainformationinelds.Theessenceof theobjectisinhowtheobjectbehavesinrelationshiptoorasaresultofitsdata,shoulditcontainany. Theexistenceofdatainanobjectisanimplementationtechniqueusedtogenerate therequiredbehaviorofthatobject. 1.2.2Classes Manyobjectsdierfromeachotheronlyinthe value ofthedatathattheyhold.Forexample,botha redcrayonandabluecrayonarecrayons;theydieronlyinthevalueofthecolorattribute,onehasared colorandtheotherabluecolor.Ourobject-orientedsystemneedsawaytocapturetheabstractionofa crayon,independentofthevalueofitscolor.Thatis,wewanttoexpressthatasetofobjectsareabstractly equivalent ,dieringonlyinthevaluesoftheirattributesandperhaps,thusdieringinthebehaviorsthat resultfromthosevalues. Manyobjectsaresimilarinmanyoverall,generalizedways,dieringonlyinsmaller,morespecicdetails. Inbiologyandotherelds,scientistsorganizeobjectsintotaxonomies,whichareclassicationhierarchies usedtoexpressthesesimilarities.Forinstance,abutteryandalobsterarequitedierent,yettheyshare thecommoncharacteristicsofallArthropods,suchasajointedexoskeleton.ThenotionofanArthropod enablesustounderstandanddealwithbutteriesandlobstersinanabstract,uniedmanner.Soonceagain wearetryingtoexpressabstractequivalence. Object-orientedsystemsuse classes toexpresstheabovenotionsofabstractequivalence. Aclassisanabstractdescriptionofasetofobjects. Aclassthuscontainthedescriptionsofallthebehaviorsoftheobjectsthatitrepresents.Incomputer scienceparlance,wecalltheindividualbehaviorsofaclassits methods .Inaddition,aclassmay,butnotalways,containdescriptionsoftheinternaldataheldbytheobjects,calledits elds ,aswellasimplementation detailsaboutitsmethodsandelds. Turningthedescriptionaround,wecansaythataclassisatemplateorrecipeforthecreationof aparticulartypeofobject.Thatis,onecanuseaclasstocreate" instantiate "objectsofthetype describedbytheclass.Becarefulnottomaketheverybeginner'scommonmistakeofequatingclassesand objects.Aclassisaspecicationofansetofobjects,itisnottheactualobject. Intechnicalterms,aclassdenesanew type inthesystem.Typesareidentiesusedtodierentiate dierentkindsofdata.Forinstance,integers,characters,stringsandarraysarealltypesofdata. 1.2.2.1ImplementationinJava ClassesarethefundamtentalbuildingblocksofJavaprograms.Deningaclassisbasicallyamatterof specifyinganamefortheclass,itsrelationshiptootherclassesandwhatsortofbehaviorstheclassexhibits aswellaswhatdataitmaycontain. SuppSupposewewantedtodeneaclasstodescribeahouseholdpet.Wecoulddoitassuch: classPet{ } Theword class aboveiscalleda keyword andcanonlybeusedtostatethatthefollowingcodeisthe denitionofaclass.The class keywordisimmediatelyfollowedbythedesirednameoftheclass, Crayon here.Thecurlybraces, {...} ,indicatetheextentofthedenitionoftheclass.Thatis,anydenitionsof theclass'sbehaviorsanddatawillbefoundbetweenthecurlybraces.Curlybracesmustthereforealways appearasamatchedset. 4 http://www.grand-illusions.com/opticalillusions/dragon_illusion/ PAGE 13 7 Ingeneral,inJava,curlybracesmarktheextentofadenition. note: TheacceptedtypographicstandardintheJavacommunityisthattheopeningcurlybrace isattheendofalineandtheendingcurlybraceisatthebeginningofitsownline.Anycode betweenthecurlybracesisindented. Well,ourclassforpetsissimple,butnotveryinterestingbecauseitdoesn'tdoanything.Wecouldsay thatourpethasaname,butpersonally,Ihavefoundthatthebehaviorofmostpetsisnotaectedbythe particularnamewegivethem.Thatis,wecangiveourpetanamebutthatdoesn'tchangethewaythey behave.Let'strysomethingelse. Petseatacertainamountoffoodperday.Petshaveacertainweight.Let'screatea model ,thatstates thatthenumberofhoursthatapetsleepsperdayisrelatedtotheamountoffoodtheyeatandtheirweight. Thuswecouldsaythatapethasabehaviorofsleepingacertainnumberofhoursdependingonitsweight andtheamountoffoodeaten. /** *Aclassthatmodelsahouseholdpet */ classPet{ /** *Theweightofthepetinlbs */ doubleweight; /** *Thenumberofhoursthepetwillsleepaftereating *thegivenlbsoffood. *@paramlbsOfFoodThenumberoflbsoffoodeaten. *@returnThenumberofhourssleptaftereatingthefood. */ doublehoursSleptdoublelbsOfFood{ return24.0*lbsOfFood/weight; } } Butwhataboutthepet'sowneraperson,supposedly?Apersonisnotsuchasimplethingasaweight. Assigninganumbertoeverypossiblepersonintheworldispossiblebutnotnecessarilythemostpractical technique.Therearemanywaystorepresentpeople:theRegistrarlikestothinkofyouasanumberwith credithoursandunpaidbills,TheCSdepartmentseesyouasa8-characterloginandunnishedgraduation requirements,yourdoctorseesyouasacollectionofpulsatingbloodvessels,cellsandbones,andyour parentsseeyouasthissweetlittlethingjustoutofdiapers.Apersonisstillaperson,butthewaythatwe choosetorepresentthemmaydierfromsituationtosituation. Buthere'sthecruxoftheissue:doesyourpetcarehowyouareinternallyrepresented?Ordoesyour petjustwantsomethingthatisapersontobetheirowner? /** *Aclassthatmodelsahouseholdpet */ classPet{ /** *Theweightofthepetinlbs PAGE 14 8 CHAPTER1.INTRODUCTION */ doubleweight; /** *Thepet'sowner */ Personowner; /** *Thenumberofhoursthepetwillsleepaftereating *thegivenlbsoffood. *@paramlbsOfFoodThenumberoflbsoffoodeaten. *@returnThenumberofhourssleptaftereatingthefood. */ doublehoursSleptdoublelbsOfFood{ return24.0*lbsOfFood/weight; } /** *Determineswhetherornotthispetishappytoseea *particularperson. *@parampThepersonwhothepetsees. *@returntrueifthePersonistheirowner,falseotherwise. */ booleanisHappyToSeePersonp{ returnp==owner; } } Herewe'veaddedaeldoftype Person ,whichisaclassusedtorepresentpeople.Itdoesn'tmatter how Person isimplemented,justthatitisarepresentationofaperson.Wecouldusetheclassdenitionof Person thatwascreatedinthemoduleonAbstractionSection1.1,orperhapsonethatisxedupalittle bit,orperhapsacompletelynewone.The Pet doesn'tcare. Thusweseethatobjectscancontainobjects.Whatdoesthissayaboutthepossiblecomplexityofa systemofobjects? 1.2.3Downloadcode Todownloadazippedlecontainingthecodeabove,clickoneofthefollowinglinks: DrJavaElementaryLanguageLevelcode:DrJava_Code.zip 5 StandardJavacode:Std_Java_Code.zip 6 BothoftheabovecodebasesincludeaDrJavaprojectle.pjtthatcanbeopenedfromDrJavatoeasily manageallthecodeandtestles. 5 http://cnx.org/content/m11708/latest/DrJava_Code.zip 6 http://cnx.org/content/m11708/latest/Std_Java_Code.zip PAGE 15 9 1.3ObjectRelationships 7 Anobject-orientedsystemcanbecharacterizedasasystemofcooperatingobjects.Someobjectsinteract onlywithcertainotherobjectsorperhapsonlywithacertainsetofobjects.Sometimesobjectsaretreatedas equivalenteventhoughtheremaybespecicdierencesbetweenthem,forinstanceasituationmaycallfora "fruit"whereuponan"apple"willdojustaswellasan"orange".Thatis,applesandorangesaretreatedas abstractlyequivalent.Conversely,thesystemdesignermaywanttoexpressthecommonalitybetweenapples andoranges.AnOOsystemhastwodistinctmechanismstoexpresstheserelationshipnotions:"is-a"which istechnicallyreferredtoas"inheritance"and"has-a"whichistechnicallyreferredtoas"composition". 1.3.1"Is-a"or"Inheritance" "Is-a"or"inheritance"sometimesalsocalled"generalization"relationshipscaptureahierarchalrelationshipbetweenclassesofobjects.Forinstance,a"fruit"isageneralizationof"apple","orange","mango" andmanyothers.Wesaythatfruitisanabstractionofapple,orange,etc.Conversely,wecansaythatsince applesarefruiti.e.anapple"is-a"fruit,thatthey inherit allthepropertiescommontoallfruit,suchas beingaeshycontainerfortheseedofaplant. UMLClassDiagramShowingInheritance Figure1.1: Theabovediagramshowsthe"is-a"relationshipbetweenApple,OrangeandMango subclassesandthemoreabstractFruitsuperclass. note: Classesarerepresentedbyboxeswiththeclassnameseparatedatthetopbyahorizontal line. note: Inheritance"is-a"lines arerepresentedbysolidlineswithsolidarrowheads.Thearrow pointsfromthesubclasstothesuperclassthink"asubclassobjectis-asuperclassobject" InJava,inheritancerelationshipsaredeclaredusingthe extends keywordwhendeclaringaclass.A subclass "extends"a superclass ,whichmeansthatthesubclassisaconcreteexampleofthemoreabstractsuperclass. Forinstance,theclass Apple wouldextendtheclass Fruit 7 Thiscontentisavailableonlineat PAGE 16 10 CHAPTER1.INTRODUCTION publicclassAppleextendsFruit{ ... } InJava,asubclassisallowedtoextendonlyasinglesuperclassno"multipleinheritance".Thisrestricts theinterpretationofahierarchaltaxomony.Asubclassisanembodimentofitssuperclass.Itisusefulto thinkofthesubclassasnotinheritingitssuperclass'sbehaviorsbutratherpossessingthesebehaviorssimply becauseit is thesuperclassthisis polymorphism Extend reallymodelswhatanobjectintrinsicallyis itstrue"being"asitwere.Thisisparticularlyusefulwhenthesuperclasshasparticularconcretebehaviors thatallthesubclassesshouldexhibit. However,"is-a"canreallybemoreofan"acts-like-a"relationship.Thisstemsfromtheperspective thatallobjectsaredenedsoleybytheirbehaviors.Wecannevertrulyknowwhatanobjecttrulyis, onlyhowit acts .Iftwoobjectsbehaveidenticallyatsomeabstractlevelthenwesaythattheyare abstractlyequivalent.Whatweneedisawaytoexpressthepurebehavioralaspectsofanobject.Java hasathekeyword implements whichisusedtoshowgeneralizationofapurebehavioralabstractioncalled an interface .Aninterfacehasasimilarsyntaxtoaclass,butonlyspeciesbehaviorsintermsofthe "signatures"theinputandoutputtypesofthemethods.Forexamplewecouldhave publicinterfaceISteerable{ publicabstractvoidturnLeft; publicabstractvoidturnRight; } publicclassTruckimplementsISteerable{ publicvoidturnLeft{ //turnthetirestotheleft } publicvoidturnRight{ //turnthetirestotheright } } publicclassBoatimplementsISteerable{ publicvoidturnLeft{ //turntheruddertotheleft } publicvoidturnRight{ //turntheruddertotheright } } note: A public class,methodoreldcanbeseenandusedbyanyone.Contrastswithprivate seenandusedonlybythatclassandpackageseenandusedonlybyclassesinthesamepackage. We'lltalkmoreabouttheselater.An abstract classormethodisapurelyabstractdenitionin thatitspeciestheexistenceofabehaviorwithoutspecifyingexactlywhatthatbehavioris.A void returntypedeclaresanon-existentreturnvalue,thatis,noreturnvalueatall. Above,TrucksandBoatsarenottaxonomicallyrelated,butyettheybothembodythebehaviorsofsteerability,suchastheabilitytoturnleftorright.Apersoncanpiloteitheraboatoratruckbasedsoleyonthe factthattheybothsupportturningleftorrightandnotbasedonwhatsortofentitytheyarefundamentally. Notethataspertheabovedenition,aclasscanimplementmultipleinterfacesatthesametime. PAGE 17 11 UMLClassDiagramShowingImplementation Figure1.2: Theabovediagramshowsthe"acts-like-a"relationshipsbetweenISteerable,Boat,and Truckclasses note: Implementation"acts-like-a"lines arerepresentedby dotted lineswithsolid arrowheads.Thearrowpointsfromthesubclasstotheinterfacethink"asubclassobjectactslike-ainterface" 1.3.2"Has-a"or"Composition" "Has-a"or"composition"sometimesreferredtoasan"associative"relationshipscapturethenotionthat oneobjecthasadistinctandpersistantcommunicationrelationshipwithanotherobject.forinstance,we cansayacar"has-a"motor.Thecarandthemotorarenotrelatedinahierarchalmanner,butinstead weneedtobeabletoexpressthatthispairofobjectshasaparticularworkingrelationship.Thecargives gastothemotorandthethemotorwillpropelthecaralong.Compositionalrelationshipscanbeone-way, whereoneobjectcan,inapersistantmanner,talktoi.e.callmethodsofasecondobjectbutthesecond objectcannot,inapersistentmanner,talkbacktotherstobject.Compositionalrelationshipscanalsobe two-way,wherebothobjectscantalktoeachotherinapersistentmanner. PAGE 18 12 CHAPTER1.INTRODUCTION UMLClassDiagramShowingComposition Figure1.3: Theabovediagramshowsthe"has-a"relationshipsbetweentheCar,MotorandWheel classes note: Composition"has-a"lines arerepresentedbysolidlineswith open arrowheads. Thearrowpointsfromtheowner"composite"totheownee"composee".Think"acomposite hasacomposee".Thenumberatthearrowheadtellshowmanycomposeesthereare,e.g.1,2,etc. "*"meansanlimitednumber,so"0...*meanszeroormoreand"1..*"meansatleastone. Theemphasismadeabovewithregardstopersistentcommunicationisdeliberateandimportant.Itisindeed possibleforanobjecttocommunicatewithanotherobjectinanon-persistentmanner.Suchnon-persistent communicationisgenerallynotthoughtofasacompositionalrelationship,butratherasadependency relationshipwheretheactionofoneobjectdependsonthatofanother.Anobjectcantellasecondobject thatitthesecondobjectneedstotalktoaspecic,perhapsthirdobject.Thesecondobjectdoesnotknow withwhomitwillbecommunicatinguntiltherstobjecttellsit.Thesecondobjectmaynot"remember"the objectitissupposedtocommunicatewithforanylengthoftimeafterthecommunicationwasaccomplished andthesecondobjectmerelywaitsfortherstobjecttotellitwithwhomtocommunicatenext.This non-persistentcommunicationisnormallyestablishedbysimplypassingthethirdtargetobjectasaninput parametertothemethodcallmadeonthesecondobjectbytherst.Notethatthethirdobjectcould actuallybetherstobject,creatinganon-persistenttwo-waycommunicationfromaninitiallyone-way communication. 1.4UMLDiagrams 8 UniedModelingLanguage"UML"istheindustrystandard"language"fordescribing,visualizing,and documentingobject-orientedOOsystems.UMLisacollectionofavarietyofdiagramsfordiering purposes.EachtypeofdiagrammodelsaparticularaspectofOOdesigninaneasytounderstand,visual manner.TheUMLstandardspeciesexactlyhowthediagramsaretobedrawnandwhateachcomponent inthediagrammeans.UMLisnotdependentonanyparticularprogramminglanguage,insteaditfocuses onethefundamentalconceptsandideasthatmodelasystem.UsingUMLenablesanyonefamiliarwithits specicationstoinstantlyreadandunderstanddiagramsdrawnbyotherpeople.ThereareUMLdiagram formodelingstaticclassrelationships,dynamictemporalinteractionsbetweenobjects,theusagesofobjects, theparticularsofanimplementation,andthestatetransitionsofsystems Ingeneral,aUMLdiagramconsistsofthefollowingfeatures: 8 Thiscontentisavailableonlineat PAGE 19 13 Entities :Thesemaybeclasses,objects,usersorsystemsbehaviors. RelationshipLines thatmodeltherelationshipsbetweenentitiesinthesystem. Generalization asolidlinewithanarrowthatpointstoahigherabstractionofthepresent item. Association asolidlinethatrepresentsthatoneentityusesanotherentityaspartofits behavior. Dependency adottedlinewithanarrowheadthatshowsoneentitydependsonthebehavior ofanotherentity. 1.4.1ClassDiagrams UMLclassdiagramsmodelstaticclassrelationshipsthatrepresentthefundamentalarchitectureofthe system.Notethatthesediagramsdescribetherelationshipsbetween classes ,notthosebetweenspecic objects instantiatedfromthoseclasses.Thusthediagramappliesto alltheobjects inthesystem. Aclassdiagramconsistsofthefollowingfeatures: Classes :Thesetitledboxesrepresenttheclassesinthesystemandcontaininformationaboutthe nameoftheclass,elds,methodsandaccessspeciers.Abstractrolesoftheclassinthesystemcan alsobeindicated. Interfaces :Thesetitledboxesrepresentinterfacesinthesystemandcontaininformationaboutthe nameoftheinterfaceanditsmethods. RelationshipLines thatmodeltherelationshipsbetweenclassesandinterfacesinthesystem. Generalization Inheritance :asolidlinewithasolidarrowheadthatpointsfromasub-classtoasuperclass orfromasub-interfacetoitssuper-interface. Implementation :adottedlinewithasolidarrowheadthatpointsfromaclasstothe interfacethatitimplement Association asolidlinewithanopenarrowheadthatrepresentsa"hasa"relationship.The arrowpointsfromthecontainingtothecontainedclass.Associationscanbeoneofthefollowing twotypesornotspecied. Composition :Representedbyanassociationlinewithasoliddiamondatthetailend.A compositionmodelsthenotionofoneobject"owning"anotherandthusbeingresponsible forthecreationanddestructionofanotherobject. Aggregation :Representedbyanassociationlinewithahollowdiamondatthetailend.An aggregationmodelsthenotionthatoneobjectusesanotherobjectwithout"owning"itand thusis not responsibleforitscreationordestruction. Dependency adottedlinewithanopenarrowheadthatshowsoneentitydependsonthe behaviorofanotherentity.Typicalusagesaretorepresentthatoneclassinstantiatesanotheror thatitusestheotherasaninputparameter. Notes thatareusedtoprovidefurtherdetailsorexplanationsofparticularpartsofthediagram. Notesareboxeswithalittle"dog-ear"ononecorner. HereisanexampleofaUMLclassdiagramthatholdsmostofthemorecommonfeatures: PAGE 20 14 CHAPTER1.INTRODUCTION UMLClassDiagram Figure1.4: Theabovediagramcontainsclasses,interfaces,inheritanceandimplementationlines, aggregationlines,dependencylinesandnotes. PAGE 21 Chapter2 PolymorphisminAction 2.1UnionDesignPattern:InheritanceandPolymorphism 1 Inheritanceandpolymorphismdiscussedbelowaretwosidesofthesamecoinandrepresentveryfoundationalconceptsinobject-orientedprogramming.Theuniondesignpatternisanexpressionofthese relationshipsandenablesustotalkabouttheminamoretangiblemanner. 2.1.1UnionDesignPattern Considerthefollowing"is-a"orinheritancerelationshipsbetween"concrete"entitiesCocaCola,sulfuric acid,milkandthe"abstract"liquidnamed" ALiquid "byconventionsinceitisanabstractentity: UnionofLiquids Figure2.1: ALiquid istheunionof CocaCola SulfuricAcid and Milk TheUMLdiagramshowsusthatCocaCola,sulfuricacidandmilkareallliquids.Conversely,the diagramtellsusthataliquidcouldbeeitherCocaCola,sulfuricacidormilk.Noteofcourse,thatliquids arenotconstrainedtothese3entitiesbutthatdoesn'taectthediscussionhereinfact,thiswillbean importantfeaturelateron. Anotherwaythatwecanexpressthenotionsdepictedbythediagramistosaythattheabstract ALiquid superclassrepresentstheunionofCocaCola,sulfuricacidandmilk.Thatis, 1 Thiscontentisavailableonlineat PAGE 22 16 CHAPTER2.POLYMORPHISMINACTION asuperclassrepresentstheunionofallofitssubclasses. orinotherwords asuperclassrepresentsallthatisabstractlyequivalentaboutitssubclasses. Forinstance,thenotionofanabstractliquidembodiesallthebehaviorsandattributessuchashavingno deniteshape,randomizedatomicpositions,freezingandboilingpointsthatarecommontoCocaCola, sulphuricacidandmilk.Notethenedistinctionbetweenhavingavalueandhavingthesamevalue. note: Ingeneral,aninterfacecanbesubstitutedfortheabstractsuperclassdiscussedherewith nolossofgenerality. Theabovediagramillustratingtherelationshipbetwenasuperclassanditssubclassesiscalledthe Union DesignPattern .Theunionpatternshowsus inheritance inhowtheCocaCola,sulfuricacidandmilk willallinherittheabstractbehaviorsofliquids,suchasthelackofadeniteshapeandfreezing/boiling points.Conversely,italsoshowsthatifasituationutilizesaliquid,eitherCocaCola,milkorsulphuric acidcanbeusedastheyareallabstractlyequivalentasliquids.Notethatthisdoesnotimplythatall threewillactidentically!Forinstance,thehumanthroatcanswallowanyliquidbecauseitismadetowork withuidsthatcanow.However,thereactionofthethroattosulphuricacidismarkedlydierentthanit reactiontomilk!Thisabilitytosubstituteanysubclassforitssuperclassandgetdierentbehavioriscalled polymorphism 2.1.1.1Abstractionvs.Commonality Asubtlebutextremelyimportantpointisthat Commonalitydoesnotimplyabstractequivalence. Justbecauseafeatureiscommontoeveryiteminaset,doesnotnecessarilymeanthatitrepresentssome sortofabstractfeatureofthoseelements.Forinstance,cats,dogs,humans,andratsareallmammalswhere amammalisdenedasananimalthatproducesmilktofeeditsyoung.Onecouldthusmakeaclassmodel whereasuperclass Mammal hassubclasses Cat Dog Human and Rat .Onecommonfeatureisbehavioris thatcats,dogs,humansandratsallgivelivebirthoftheiryoung.Soitistemptingtosaythatthe Mammal classshouldalsoembodythe"livebirth"behavior.However,asonewanderstheworlddiscoveringnew mammals,inthebackwatersofAustraliaonendstheduck-billedplatypus 2 whichproducesmilkandis thereforeclearlyamammal.However,theduck-billedplatypusalsolayseggs.Thusthe"livebirth"behavior doesnotbelonginthe Mammal superclassasitwasonlyacoincidencethatitwascommontoourinitialset ofsubclasses.Moreimportantly,beingabletogivelivebirthwasneverpartoftheabstractdenitionofa mammalandthusshouldneverhavebeenincludedinthe Mammal superclassintherstplace. Cats,monkeysandwhales,whilediversecreatures,areallmammals.Hencetomodelsuchasystemin thecomputer,itmakessensetomake Cat Monkey and Whale allsubclassesofanabstract Mammal superclass. EachspecieshasmanybehaviorsmethodsbutIwillonlyconcentrateon3inparticular: 1. booleangivesMilk :returnstrueiftheanimalcangivemilktofeeditsyoung,falseotherwise 2. StringmakeSound :returnsaStringrepresenationofacommonsoundtheanimalmakes. 3. booleangivesLiveBirth :returnstrueiftheanimalbearsliveyoung. Inthetablebelowarethemethodsandwhathappenswheneachspeciesexecutesthatmethod: 2 http://www.creationscience.com/onlinebook/LifeSciences13.html PAGE 23 17 Mammal Method booleangivesMilk StringmakeSound boolean givesLiveBirth Cat true "Meow" true Monkey true "Screech" true Whale true "[whalesong]" true Table2.1 WecouldstartoutwiththefollowingclassimplemenationMammal0.java 3 : ModelofMammals Figure2.2: Nocommonmethodsdenedinthesuperclass. note: Italicssignifyabstractmethodsorclasses note: return_value:method_nameparameter_type_#1parameter_name_#1, parameter_type_#2parameter_name_#2,etc Let'sstartouranalysis: Amammalisdenedbythefactthatitgivesmilktofeeditsyoung.Itisthusnotsurprisingthat allthe givesMilk methodsinthesubclassesreturntrue.The givesMilk methodisaprime candidatefor"hoisting"upintothe Mammal superclass"hoisting"=movingthemethodupwards fromthesubclasstothesuperclass. makeSound returnsadierentvalueforeachspecies,butintrisically,weexpectanyanimal,which includesmammals,tobeabletomakesomesortofsound.Thus Mammals shouldhavea makeSound method,butsince,atthe Mammals level,wedon'tknowexactlyhowthatsoundwillbemade,the methodatthatlevelmustbeabstract.The makeSound methodattheconcrete Cat Monkey and Whale levelhowever,wouldbeconcretebecauseeachanimalmakesitsownuniquesound. 3 http://cnx.org/content/m11796/latest/Mammal0.java PAGE 24 18 CHAPTER2.POLYMORPHISMINACTION givesLiveBirth returnsexactlythesamevalueforallofourratherdiverseselectionofanimals here.Itseemslikeanecandidateforhoisting.Orisit....?Let'sgoaheadanhoistitanyway. ThisiswhatwehavesofarMammal1.java 4 : ModelofMammals Figure2.3: Abstractandcommonmethodshoistedtothesuperclass. Beforewegochargingahead,let'sstopforamomentandreviewwhatwe'vedone:Cats,monkeys,and whalesdorepresentawidespectrumofmammals,butremember,theabstract Mammal classisarepresentation of ALL mammals,notjusttheoneswehavesofar.Thecorrelationoflikebehaviorwithallourrepresented animalsdoesnotimplyitsinclusionintheirabstractrepresentation! Forinstance,oneday,inourwanderingsthroughAustralia,weencounteraDuckbilledPlatypus 5 .Let's seehowitbehaveswithrespecttoour3methods: Mammal Method booleangivesMilk StringmakeSound boolean givesLiveBirth DuckbilledPlatypus true "growl" false Table2.2 Duckbilledplatypuslayeggs!! Givinglivebirthisnotpartofthedenitionofamammal.Ontheotherhand,thequestionofwhether ornottheanimalgiveslivebirthcanalwaysbeaskedofanyanimal,includingallmammals.Theresultmay betrueorfalsehowever,sothemethodmustbeabstractatthe Mammal level. OurclassstructureshouldlooklikethisMammal2.java 6 : 4 http://cnx.org/content/m11796/latest/Mammal0.java 5 http://en.wikipedia.org/wiki/Duckbilled_platypus 6 http://cnx.org/content/m11796/latest/Mammal0.java PAGE 25 19 ModelofMammals Figure2.4: Properlyabstractedmodel. Hoistingdoesnotguaranteeproperabstraction.Hoistingshouldbedrivenbyaneedforabstraction,notbycoincidence. Anotherkeynotionthattheunionpatternemphasizesis levelsofabstraction .Whatweseeisthat theconceptofaliquidismoreabstractthanmilk.Inturn,thegeneralconceptofmilkismoreabstract than"2%milk"or"skimmilk"whichwouldbesubclassesofmilk.Ingeneralwecanseethatasuperclass isadistinctlyhigherlevelofabstractionthananyofitssubclasses.Oneofthekeytoolsweusetohelp usdesignandbuildhighqualityobject-orientedsystemsiscarefulattentiontotheabstractionlevelatany givenmoment. GoodOOPcodealwaysmaintainsaconsistentlevelofabstraction. Abstractionlevelsarelinksinachain.Achainisonlyasstrongasitsweakestlink.Aprogramisonlyas abstractasitslowestabstractionlevel. LevelsofabstractionillustrateanotherimportantaspectofanOOprogram.Sinceasuperclassrepresents theunionofthesubclassesorconversely,thatthesuperclasscanberepresentedbyanyofitssubclasses, weseethatthesuperclassisanembodimentofallthe invariant aspectsofthesubclasses.Thatis,the superclass'sdenitionisallthatisabstractlyequivalentaboutthesubclassesallthatdoesnotchangefrom subclasstosubclass.Notethatthisdoes not implythatthevaluesofcommoneldsarenecesarilythe same,justthat,perhaps,thattheeldexists.Notdoesitimplythatwhatiscommontoallthesubclasses isnecessarilywhatisabstractlyequivalentaboutthemseethenoteabove.Thedierencesbetweenthe subclassesiswhatcreatesthevariationsinhowtheprogrambehaveswhenanygivensubclassisusedin placeofthesuperclass.Wecallthisthe variant aspectsofthesystem. Thetotalbehaviorofaprogramisthecombinationofitsvariantandinvariantbehaviors. 2.1.2InheritanceandPolymorphism Inheritanceandpolymorphismarereallyjusttwowaysoflookingatthesameclassrelationship. Inheritanceislookingattheclasshierarchyfromthebottomup.Asubclassinheritsbehaviorsand attributesfromitssuperclass.Asubclassautomaticallypossessescertainbehaviorsand/orattributessimply PAGE 26 20 CHAPTER2.POLYMORPHISMINACTION becauseitisclassiedasbeingasubclassofanentitythatpossessesthosebehaviorsand/orattributes.That is,acherrycanbesaidtoautomaticallycontainaseedbecauseitisasubclassofFruitandallfruitcontain seeds. Inheritanceisusefulfroma codereuse perspective.Anynon-privatecodeinthesuperclassdoesnot havetobereplicatedinanyofthesubclassesbecausetheywillautomaticallyinheritthosebehaviorsand attributes.However,onemustbeverycarefulwhentransferringcommoncodefromthesubclassestothe superclassaprocesscalled" hoisting ",astheproperabstractionrepresentedbythesuperclassmaybe brokenseenoteabove. Polymorphism,ontheotherhand,islookingattheclasshierarchyfromthetopdown.Anysubclass canbeusedanywherethesuperclassisneededbecausethesubclassesareallabstractlyequivalenttothe superclass.Dierentbehaviorsmayarisebecausethesubclassesmayallhavedierentimplementations oftheabstractbehaviorsdenedinthesuperclass.Forinstance,allliquidshaveaboilingtemperature. Theymayhavedierentvaluesforthatboilingtemperaturewhichleadstodierentbehaviorsatanygiven temperature. Polymorphismisarguablythemoreusefulperspectiveinanobject-orientedprogrammingparadigm. Polymorphismdescribeshowanentityofalowerabstractionlevelcanbesubstitutedforanentityofa higherabstractionlevelandintheprocess,changetheoverallbehavioroftheoriginalsystem.Thiswillbe thecornerstonethatenablesustobuildOOsystemsthatareexible,extensible,robustandcorrect. 2.1.3ExploringPolymorphism Let'sexploresomedierentwaysinwhichpolymorphismpresentsitself.Considerthefollowingexampleof theuniondesignpattern: /** *Aninterfacethatrepresentsanoperationontwodoubles */ publicinterfaceIBinaryOp{ doubleapplydoublex,doubley;//allinterfacemethodsarepublicandabstractbydefault } /** *AnIBinaryOpthataddstwonumbers */ publicclassAddOpimplementsIBinaryOp{ publicdoubleapplydoublex,doubley{ returnx+y; } } /** *AnIBinaryOpthatmultipliestwonumbers */ publicclassMultOpimplementsIBinaryOp{ publicdoubleapplydoublex,doubley{ returnx*y; } publicStringgetDescription{ return"MultOpisamultiplyingfunction."; } PAGE 27 21 } Exercise2.1 Solutiononp.35. Isthefollowinglegalcode? IBinaryOpbop=newIBinaryOp ; Exercise2.2 Solutiononp.35. Isthefollowinglegalcode? IBinaryOpbop=newAddOp ; Exercise2.3 Solutiononp.35. Giventheabovedeclarationandassignmentof bop ,isthefollowingassignmentthenpossible? bop =newMultOp ; Exercise2.4 Solutiononp.35. Supposewehave bop=newAddOp ;,whatistheresultof bop.apply,3 ? Exercise2.5 Solutiononp.35. Supposewenowsay bop=newMultOp ,whatistheresultof bop.apply,3 now? Exercise2.6 Solutiononp.35. Supposewehavesomevariable,called myOp oftype IBinaryOp whatistheresultof myOp.apply,3 ? Exercise2.7 Solutiononp.35. Supposewehave bop=newMultOp ,isitlegaltocall bop.getDescription ? Exercise2.8 Solutiononp.35. Isthefollowinglegalcode? AddOpaop=newAddOp Exercise2.9 Solutiononp.35. Giventhedeclarationinthepreviousexercise,isthefollowinglegal? aop=newMultOp Exercise2.10 Solutiononp.35. Supposewehavedenitionsof aop and bop fromabove.Isthefollowinglegal?Thatis,canwe compileandrunthefolowingstatementwithouterror? bop=aop; Exercise2.11 Solutiononp.35. Istheconverselegalaswell?Thatis,usingtheabovedenitions,canwecompileandrunthe followingstatement? aop=bop; 2.2Ballworld,inheritance-based 7 InthismodulewewillexploremanyOOPconceptsbyexaminingtheprogram"Ballworld".Downloadthe codeforBallworldhere 8 7 Thiscontentisavailableonlineat PAGE 28 22 CHAPTER2.POLYMORPHISMINACTION UMLclassdiagramofBallworld Figure2.5: Notetheuniondesignpatternw.r.t. ABall anditssubclasses. TorunBallworld,loadthelesintoDrJavaandright-clicktheBallControlle.Select" RunDocument's MainMethod "toruntheprogram.Fromthecommandline,gototheuppermostBallworlddirectory andcompileallthelesinboththedirectories" javacballworld/*.java "and" javaccommand/*.java "and thenruntheprogramassuch:" javaballworld.BallControl ".The MakeBall buttoncreatesaninstanceof whatever ABall classistypedintothetexteldontheleft.The" ClearAll "buttonclearsanyballsoof thescreen. Inanutshell,thewayBallworldworksisakintoaip-bookanimation:The BallControl classcontains PAGE 29 23 a Timer that"ticks"every50milliseconds.Everytimethetimerticks,thepanelinthe BallGUI uponwhich theballsaretobedrawnisrequestedtorepaintitself.Whenthepanelrepaints,italsotellsthe Dispatcher tonotifyevery ABall inthesystemtoupdateitself.Whenan ABall updates,itupdatesanyinternal valuesithasits"state"suchasitscolor,radius,and/orvelocity.Itthenmovesitspositionbyanamount correspondingtoitsvelocityanddraws"paints"itselfontothepanel.Sincethisishappening20timesa second,theballsappeartobemovingand/orchangingandthustheanimationisacheived.The ILambda interface3enablesthe BallGUI tocommunicateinageneric,decoupledmannertothe BallControl and the Randomizer classisautilityclassthatprovidesmethodstoproducevariousrandomvaluesneededby thesystem.MuchofthecodeinBallworldissignicantlymoresophisticatedthanwhathasbeencovered inthecoursesofaritwillbecoveredsoon,don'tworry! 2.2.1AbstractClasses First,wewillfocusontheuniondesignpatternbetween ABall WanderBall CurveBall and StraightBall Inauniondesignpattern,weseethatthesuperclassrepresentsanabstractionoftheunionofitssubclasses. Forinstance,afruitisanabstractionofspecicconcreteclassessuchasappleandpear.Afruitembodies thecommoncharacteristicsofitssubclassesevenifitdoesn'tcompletelydescribetheexactnatureofthose characteristics.Inafruit,thereisaseed.However,thenotionof"fruit"doesn'tspecifyexactlythenumber, size,colororshapeofitsseeds.Itonlyspeciesthatitdoesindeedhaveaseed.Likewise,afruithasthe behaviorofripening.Apples,oranges,andbananasallripendierentlyandatdierentrates.Theabstract fruitnotiondoesnotspecifythespecicnatureoftheripeningbehavior,justsimplythatitdoeshavethat behavior.Insuch,weseethatwecanneverhaveafruitthatisnotaspecicclassoffruit,suchasanorange orgrape. Correspondingtotheabovenotions,abstractclassesinJavacannotbeinstantiated.Abstractclassesare denotedbythe abstract keywordintheclassdenition: publicabstractclassAFruit{...} Byconvention,theclassnamesofabstractclassesalwaysbeginwith"A". InBallworld, ABall isanabstractclassrepresentingacircularballthathasanumberofproperties:a color,aposition,avelocity,etc.Theabstractballalsohassomedeningbehaviors,suchasthatallballs shouldpaintalled,coloredcirclewhenrequestedtodisplaythemselvesonagraphicscontextapanel. Likewiseallballsknowhowtobounceothewallsofthecontainer.Theseconcretebehaviorsarecalled "defaultbehaviors"becauseallsubclassesof ABall ,suchas StraightBall and CurveBall ,automatically getthesebehaviorsbydefault.Oneofthemostcommonandusefulreasonsforusinganabstractclassisto beabletodenethedefaultbehaviorsforallthesubclasses. 2.2.1.1AbstractMethods Butwhatabouttheabstractbehaviorsthatabstractclassesexhibit?Forinstancetheabstract"ripening" behaviorofafruit?Attheabstractionlevelofafruit,theexactimplentationofripeningcannotbespecied becauseitvariesfromoneconcretesubclasstoanother.InJava,thisisrepresentedbyusingthekeyword abstractaspartofthesignatureofamethodwhichhasnocodebody: publicabstractclassAFruit{ //restofthecode publicabstractvoidripen; } Thereisnocodebodybecauseitcannotbespeciedatthisabstractionlevel.Allthattheabovecodesays isthatthemethoddoesexistinall AFruit .Thespecicimplmentationofmethodislefttothesubclasses, wherethemethodisdeclaredidenticallyexceptforthelackofthe abstract keyword: PAGE 30 24 CHAPTER2.POLYMORPHISMINACTION publicclassMangoextendsAFruit{ //restofcode publicvoidripen{ //codetoripenamangogoeshere } } publicclassTomatoextendsAFruit{ //restofcode publicvoidripend{ //codetoripenatomatogoeshere } } Thetechnicaltermforthisprocessiscalled overriding .Wesaythattheconcretemethodsinthesubclasses override theabstractmethodinthesuperclass. Notethatifaclasshasanabstractmethod,theclassitselfmustbedeclared abstract .Thissimply becausethelackofcodeintheabstractmethodmeansthattheclassconnotbeinstantiated,orperhapsmore importantly,itsaysthatinorderforaclasstorepresentabstractbehavior,theclassitsemustrepresent anabstractnotion. Overridingisnotlimitedtoabstractmethods.Onecanoverrideanyconcretemethodnotdeclaredwith the final keyword.Wewilltendtoavoidthistechniquehowever,asthechangingofbehaviorasonechanges abstractionlevelsleadstoveryunclearsymanticsofwhattheclassesareactuallydoing. InBallworldweseetheabstractmethod updateState .Abstractmethodsandclassesaredenotedin UMLdiagramsbyitaliclettering.Thismethodiscalledbythe update methodaspartoftheinvariant processofupdatingtheconditionoftheballevery50milliseconds.Theupdatemethoddoes4things: 1.Updatethestateoftheballbycallingtheabstract updateState method. 2.Movetranslatethepositionoftheballbyaddingthevelocitytoit. 3.Checkiftheballneedstoboundoawall. 4.Painttheballuponthescreen. Thistechniqueofcallinganabstractmethodfrominsideofaconcretemethodiscalledthe template methoddesignpattern whichwewillgettolaterinthecourse. ABall.updateState isabstractbecauseattheabstractionlevelof ABall ,oneonlyknowsthatthe ballwilldenitelydosomethingwithregardstomodifyingperhapsitsinternaleldvaluesits"state". Eachsubclasswilldoitdierentlyhowever.The StraightBall willdonothinginits updateState method becauseaballwithaconstantunchangingvelocitywilltravelinastraightline.Remember, doingnothing isdoingsomething !The CurveBall 's updateState methodusessinesandcosinestoturnthevelocity byaxedthoughrandomlychosenangleateveryupdateevent.Youcanimaginethatotherpossible subclasssescoulddothingssuchasrandomlychangethevelocityorchangetheradiusoftheballorchange thecoloroftheball. ThereisnocodeintheentireBallworldsystemthatexplicitlyreferencesanyoftheconcrete ABall subclasses.Allofthecoderunsatthelevelofabstractionofanabstractball.Thedierencesinbehaviorof thevariousballsmadeonthescreenusingthedierentconcretesubclassesisstrictlydueto polymorphism Newtypesofballscanbeaddedtothesystemwithoutrecompiling any oftheexistingcode.Infact,new typesofballscanbeaddedwithoutevenstoppingtheBallworldprogram! PAGE 31 25 2.2.2Abstractclassesvs.Interfaces Subclasseshaveadierentrelationshipbetweeninterfacesandabstractsuperclasses.Asubclassthatimplementsaninterfaceissayingsimplythatit"actslike"thatspeciedbytheinterface.Theclassmakesno statementshoweveraboutfundamentallywhatitactuallyis.Anactorimplementsaercesomealienfroma distantplantetinonemovieandacklefelineinanother.Butanactorisactuallyneither.Justbecausethe actorprotrayedainterplanetaryalien,doesn'tmeanthattheactorfundamentallypossessedalltheabilities ofsuchanalien.Allitsaysisthatinsofarthecontextinwhichtheactorwasutilizedasthealien,the actordidimplementallthenecessarybehaviorsofthealien. Asubclassisfundamentallyanexampleofitssuperclass.Asubclassautomaticallycontainsallthe behaviorsofitssuperclassbecauseitfundamentally is thesuperclass.Thesubclassdoesn'thavetoimplement thebehaviorsofitssuperclass,italreadyhasthem.Anactorisahumanandbythatright,automatically possessesallthatwhichmakesahuman:onehead,twoarms,10toes,etc.Notethatthisistrueevenifthe abstractclasshas100%abstractmethodsitstillenforcesastricttaxonomicalhierarchy. implements isabout behaving extends isabout being 2.2.3Variantvs.InvariantBehaviors AcrucialobservationisthatthetheBallworldcodethatmanagestheGUI BallGUI andtheballmanagement BallControl Dispatcher ,etc.onlydealwiththeabstractball, ABall .Thatis,theyrepresent invariant behaviorattheabstractballlevel.Thedisplay,creationandmanagmentoftheballsisindependentoftheparticularkindsofconcreteballsthatisbeinghandled.ThemainBallworldframeworkcanthus handle any typeof ABall ,past,presentandfuture. StraightBall CurveBall and WanderBall arethusconcretevariantsof ABall .Theyrepresentthe variant behaviorsofthesystem.Otherthanintheirconstructorswhichwillprovetobeasignicant pointwhenthisinheritance-basedmodeliscomparedtoamoreadvancedcomposition-basedmodel,these concretesubclassesonlycodetheabstractvariantbehaviorassociatedwithaball,namelythe updateState method.Inheritancegivesanyinstantiationoftheseclassesboththeinvariantbehaviorsfromthe ABall superclassplusthevariantbehaviorsfromthesubclass. TheBallworldcodedemonstratestheimportanceoftheconceptof separationofvariantandinvariant behaviors Clearlyandcleanlyseparatingthevariantandinvariantbehaviorsinaprogramiscrucialfor achievingexible,extensible,robustandcorrectprogramexecution. Whereandhowtoseparatethevariantandinvariantbehaviorsisarguablythemostimportantdesign considerationmadeinwritinggodsoftware. 2.2.4JavaSyntaxIssues 2.2.4.1Packages PackagesarewaythatJavaorganizesrelatedclassestogether.Packagesaresimplydirectoriesthatcontain therelatedcodeles.Eachclassleinapackagedirectoryshouldhavetheline packageXXX; atitstop, wherethe XXX matcheswiththedirectory.name.Ifneither public nor private nor protected i.e.a blankspecierisusedtospecifythevisibilitylevelofaclassormethod,thenthatmethodcanbeseenby othermembersofthepackagebutnotbythoseoutsideofthepackage.Tousethepublicclassesinapackage, the importmyPackage.*; syntaxisused.ThistellstheJavacompilertoallowallthepublicclassesinthe myPackage directory.Packagescanbenested,thougheachlevelmustbeimportedseparately. PAGE 32 26 CHAPTER2.POLYMORPHISMINACTION 2.2.4.2Staticeldsandmethods Staticeldsandmethods,denotedbythe static keywordintheirdeclarations,areeldsandmethodsthat canbeaccessedataclasslevel,notjustanobjectlevel.Ingeneralthesearevaluesorbehaviorsthatone wishesforallinstancesofaclasstohaveaccessto.Thesevaluesandbehaviorsarenecessarilyindependent ofthestateofanyparticularinstance.Staticeldsandmethodsareoftenreferredtoas" classvariables and" classmethods ". Anexamplesofaclassvariablesare Math.PI and Color.BLUE or Color.RED .Theseareuniversalvalues associatedwithmathandcolorrespectivelyandthusdonotneedanobjectinstancetobeviable.By convention,allstaticeldnamesareinallcapitolletters.Astaticeldisreferencedsimplybywritingthe classnamefollowiedbyaperiodandthenbytheeldname.Noinstantiationsarenecessary. The Randomizer classcontainsnumerousstaticmethods.Thisisbecauseeachofthemethodstoproduce variousrandomvaluesisindependentofeachotherandthattheprocessineachmethoddoesnotaectnor isaectedbythestateoftherestoftheclass.Essentially,thisentailsthattheclasscontainnonon-static elds.Aclassassuchisreferredtoasbeing" stateless ".Justlikeastaticeld,astaticmethodisinvoked inthesamemannerasthestaticelds: ClassName.staticMethodName... Classeswithstaticmethods areusuallyutilityclassesthatareusedtoholdasetofrelatedfunctionalprocesses,e.g. Randomizer holds acollectionofrandomvaluegenerators.Likewise, Math holdsacombinationofstaticvalues,suchas PI andstaticmethodssuchas sin and cos Thereisoneveryspecialstaticmethodwiththefollowing exact signature: publicstaticvoidmainString[]args Thismethod,foundin BallControl ,isthemethodthatJavausestostartprogramsup.SinceOOprograms aresystemsofinteractingobjects,thisstatic"main"methodisusedtocreatetherstobjectsandgetthe programupandrunning.SowhenJavastartsaprogram,itlooksforthisandonlythismethod. 2.2.4.3Callingmethodsofthesuperclass Whenconcretemethodsortheconstructorofasuperclassareoverriden,sometimesitisnecessaryordesirable tocalltheoriginalsuperclassbehaviorfromthesubclass.Acommonreasonforthisisthatthesubclass's behaviorissimpleanadditiontothesuperclassbehavior.Onedoesnotwanttoreplicatethesuperclass code,soacalltothesuperclass'soriginalmethodsisrequiredatsomepointinthesubclassesoverriding method.Toaccomplishthis,Javausesthe super keyword. super referstothesuperclassinstance,just as this referstotheclassinstanceitselfthesubclasshere.Notethattechnically, super and this are thesameobjectthinkofitasthedierencebetweenthe id andthe ego .Doesthatmeanthatacoding mistakewiithrespectto super and this isaFreudianslip? Supposethesuperclasshasamethodcalled myMethod whichthesubclassoverides.Forthesubclass tocallthesuperclass's myMethod ,itsimplyneedstosay super.myMethod .Contrastthistothesubclass callingitsown myMethod : this.myMethod note:Javasyntaxrulesallowforthe this tobeomitted. Tomakeacalltothesuperclass'sconstructorthesubclasssimplysays super... ,supplyingwahtever parametersthesuperclassconstructorrequires.Thisisaverycommonscenarioasthethesubclassalmost alwaysneedstosuperclasstoinitializeitselfbeforeitcanperformanyadditionalinitializations.Thusthe super... callmustbetherstlineinthesubclass'sconstructor.Iftheno-parameterconstructorofthe superclassisrequired,thecallto super canbeomittedasitwillbeautomaticallyperformedbytheJava run-timeengine.Thisofcoursepresumesthatthesuperclass'sno-parameterconstructorexists,whichit does not ifaparameterizedconstructorhasbeendeclaredwithoutexplicitlydeclaringtheno-parameter constructor. PAGE 33 27 2.3Ballworld,composition-based 9 Inthismodulewewillexplorewhatisgainedbymodifyingtheinheritance-basedBallworldsystemSection2.2intoacomposition-basedsystem. Intheinheritance-basedBallworldsystem,wewereabletogeneratequiteabitofexibilityandextensibility.Forinstance,wecoulddevelopnewkindsofballsandaddthemintothesystemwithoutrecompiling therestofthecode.Thiswasaccomplishedbyhavingtheinvariantballcreationandmanagementcodedeal onlywiththeabstractballwhilethevariantbehaviorswereencapsulatedintotheconcretesubclasses. 2.3.1TheProblemwithInheritance Inheritanceseemstoworkquitewell,butsupposewewanttodomorethanjustputdierentkindsofballs onthescreen?Whatifwewantedtobeabletochangehowaballbehaves, after ithasbeencreated?What ifwewantcreateballsthatdoamultipleofdierentbehaviors,suchaschangecolorandradius?While workingsolutionsusinganinheritance-basedsystemdoexist,theyarecumbersome,inecientandmost importantly,inconsistentwithanysortofclearabstractmodelofwhatballsshouldbelike. Theproblemliesintheverynatureofinheritance.Whenweattemptedtoseparatethevariantfromthe invariantbehaviors,weoverlookedacrucialaspectofinheritance.Inourmodel,thesuperclassrepresented theinvariantbehaviorsofaballwhilethesubclassesrepresentedthevariantbehaviors.Theseparation seemedclearenoughintheUMLdiagram,exceptthatwhenonehasanactualobject instance both the superclassandsubclassbehaviorsareboundintoa single entity.Aball object cannotchangeitsvariant updateState behaviorbecauseitisinextricablyboundwithtotheinvariantbehaviors.Aballobjectcannot becomposedofmultiple updateState behaviorsbecausethatcodecannotbeisolatedfromtherestofthe ball'scode.Ifyouwantacurvingbehavior,youhavetogetitpackagedinawholeballobjectyoucan'tget justthebehavior. Aclearsymptonofthisproblemisthecommoncodetocallthesuperclassconstructorfoundinallthe subclasses'constructors.Thistellsusthatthesuperclassisreallyrightthereinthesubclasswitheverything else.Thefactthatthecodeisrepeatedfromclasstoclasssaysthatitisinvariantcodeinthemiddleof whatwewanttobevariantcode. Theinheritance-basedmodelofBallworlddoesnotseparatethevariantandtheinvariantatthe properplace.Thereisinvariantcodemixedtogetherwiththevariantcode. That'swhytheycan'tbeseparatedandtheinvariantbehaviorsaredraggedalongwiththevariantbehaviors. Thisiswhatmakesdynamicallychangingbehaviorsandmultiplycomposedbehaviorssodicultinthis system. 2.3.2PizzasandShapes Tounderstandwhatwecandotoremedytheproblemswithourinheritance-basedmodel,let'sdigressfor abitandconsiderasimplemodelofpizzas.Here,wehaveapizzawhichhasapriceand hasa shape.A shape,beitacircle,square,rectangleoftriangle,iscapableofdeterminingitsownarea.Apizza,when requestedtocalculateitspricepersquareinch,simplytakesitspriceanddividesitbytheareaofitsshape. Toobtainthatarea,the Pizza delegates tothe IShape ,sinceitistheshapethatknowshowtocalculate itsarea,notthepizza. 9 Thiscontentisavailableonlineat PAGE 34 28 CHAPTER2.POLYMORPHISMINACTION PizzasandShapes Figure2.6: Apizza has-a shape,whichisabletocalculateitsarea. Delegationisthehandingofacalculationotoanotherobjectforitprocess.Here,thepizzaisonly interestedintheresultoftheareacalculation,nothowitisperformed. Tothepizza,theshaperepresentsanabstractalgorithmtocalculatethearea. The Pizza andthe IShape classesrepresenttheinvariantprocessesinvolvedwithcalculatingtheprice persquareinchration,whiletheconcrete Circle Square Triangle and Rectangle classesrepresentthe variantareacalculationsfordierentshapes.Whatweeseefromthisexampleisthat objectscanbeusedtorepresentpurebehavior,notjusttangibleentities. Interfacesareparticularlyusefulhereastheyareexpresslydesignedtorepresentpure,abstractbehavior. 2.3.3FromInheritancetoComposition ComingbacktoBallworld,weseethatthe updateState methodin ABall isanabstractalgorithmto updatethestateoftheball.So,justasinthepizzaexample,wecanrepresentthisalgorithm, andjust thisalgorithm ,asanobject.Wecansaythataball hasan algorithmtoupdateitsstate.Anotherwa ofsayingthisistosaythattheballhasa strategy toupdateitsstate.Wecanrepresentthisbyusing composition.Insteadofhavinganabstractmethodtoupdatethestate,wemodelaballashavingareference toan IUpdateStrategy object.Thecodeforupdatethusbecomes publicvoidupdateObservableo,Objectg { _strategy.updateStatethis;//updatethisball'sstateusingthestrategy location.translatevelocity.x,velocity.y;//movetheball PAGE 35 29 bounce;//bouncetheballoffthewallifnecessary paintGraphicsg;//painttheballontothecontainer } Theballhandsareferencetoitself, this ,tothestrategysothatthestrategyknowswhichballtoupdate. Thevariantupdatingbehaviorsarenowrepresentedbyconcreteimplementationsofthe IUpdateStrategy interface. Composition-basedBallworld Figure2.7: Ball isnowaconcreteclassanditssubclasseshavebeeneliminatedinfavorofbeing composedwithanabstractstrategy. Notethatthe Randomizer classhasbeenredesignedtoeliminateitsstaticmethods.Onenewmethod hasbeenaddedaswell. Thereareanumberofveryimportantpointstonoticeaboutthisnewformulation: Themodied ABall classnowcontains100%concretecodeandthusshouldnotbeabstractanymore. ABall hasbeenrenamedtosimply Ball Accessormethodsforthestrategy getStrategy and setStrategy havebeenadded. The Ball classisstill100%invariantcode. PAGE 36 30 CHAPTER2.POLYMORPHISMINACTION The CurveBall StraightBall ,etc.subclassesarenolongerneededastheirvariantbehaviorshave beenmovedtothe IUpdateStrategy subclasses. Eectivelywhathashappenedisthatthe updateState methodhasbeenmovedfromthe ABall subclassesandembodiedintotheirownclasses. The IUpdateStrategy subclassesdonotinheritanythingfrom Ball ,hencetheydonotcontain anyinvariantcode. Thestrategiesarethus100%variantcode. Thereferencetotheballduringtheupdatingprocesshasgonefromaperistentcommunicationlink implicitly, this ,toatransientcommunicationlink host Thiscomposition-basedmodeldividesthecodeexactlybetweenthevariantandinvariantbehaviors thisisthekeytothepowerandexibilityitgenerates. Thisnewcomposition-basedmodelofBallworldisanexampleoftheStrategyDesignPattern 10 .The strategydesignpatternallowsustoisolatevariantbehaviorsonamuchnerlevelthansimpleinheritance models. 2.3.3.1ComposingBehaviors Sofar,allofourredesigninghasresultedinasystemthatbehavesexactlyasitdidwhenwestarted.But whatonendsveryoftenindevelopingsystemsisthatinordertomaketwostepsforward,onemustrst makeonestepbackwardsinordertofundmentallychangethedirectioninwhichtheyaregoing.So,even thoughitlookslikeoursystemhasnotprogressedbecauseitstilldoesexactlythesamething,weareindeed inaverydierentposition,architecturally.Byfreeingthevariantbehaviorsfromtheinvariantones,we havegeneratedatremendousamountofexibility. 2.3.3.1.1Ballsthatchangetheirstrategies Let'sconsiderathenotionofaballthatchangesitsbehavior.Sincewehavemodeledaballas having a strategy,wecansimplysaythatinsomemanner,itistheball's strategy thatchanges.Wecouldsaythat theballchangesitsstrategy,butsincetheballdoesn'tknowwhichstrategyithastobeginwith,itreally doesn'tknowonestrategyfromanother.Onecouldarguethatitthereforecan'tknowwhenorifitshould everchangeitsstrategy.Therefore,theballcannotbecodedtochangeitsownstrategy!So,whosebaliwick isthechangingofthestrategy? Sincethechangingofastrategyisastrategyforupdatingtheball,itisthestrategythatdeterminesthe change.Thestrategychangesthestrategy!Let'sconsiderthefollowingstrategy: packageballworld; importjava.awt.*; publicclassChange1StrategyimplementsIUpdateStrategy{ privateinti=500;//initialvaluefori publicvoidupdateStateBallcontext{ ifi==0context.setStrategynewCurveStrategy;//changestrategyifireacheszero elsei--;//notyetzero,sodecrementi } } 10 http://www.exciton.cs.rice.edu/JavaResources/DesignPatterns/StrategyPattern.htm PAGE 37 31 Thisstrategyactsjustlikea StraightStrategy for500updatesandthenittellstheballits context toswitchtoa CurveStrategy .Oncethe CurveStrategy isinstalled,theballbecomescurving,without theneedforanysortofconditionalstodecidewhatitshoulddo.Thecontextballfundamentallyand permanently becomes curving. Exercise2.12 Solutiononp.35. Whatwouldhappenifyouhadtwostrategiesliketheoneabove,butinsteadofreplacingthemselves with CurveStrategy 's,theyinsteadinstantiatedeachother? Akeynotionaboveisthatastrategycancontainanotherstrategy.Intheaboveexample,the Change1Strategy couldhaveeasilypre-instantiatedthe CurveStrategy andsaveditinaeldforuse whenitwasneeded.Butthedoesitmatterexactlywhichconcretestrategyisbeingused?Ifnot,why notworkatahigherabstractionlevelandletonestrategyholdareferencetoan abstract strategy?For instance,considerthefollowingcode: packageballworld; importjava.awt.*; publicclassSwitcherStrategyimplementsIUpdateStrategy{ privateIUpdateStrategy_strategy=newStraightStrategy; publicvoidupdateStateBallcontext{ _strategy.updateStatecontext; } publicvoidsetStrategyIUpdateStrategynewStrategy{ _strategy=newStrategy; } } Thisstrategydoesn'tlooklikeitdoesmuch,butlooksaredeceiving.Allthe SwitcherStrategy doesisto delegatethe updateState methodtothe _strategy thatitholds.Thisdoesnotseemmuchinofitself, butconsiderthefactthatthe SwitcherStrategy alsohasasettormethodfor _strategy .Thismeans thatthestrategyheldcanbechangedatruntime!Moreimportantly,supposeaballisinstantiatedwith a SwitcherStrategy .Thebehavioroftheballwouldbethatofwhateverstrategyisbeingheldbythe SwitcherStrategy sincetheswitcherjustdelegatestotheheldstrategy.Ifoneweretohaveareferenceto that SwitcherStrategy instancefromsomewhereelse,onecouldthenchangetheinternalstrategy.Theball isnonethewiserbecauseallithasisareferencetothe SwitcherStrategy instance,whichhasn'tchanged atall!However,sincetheheldstrategyisnowdierent,theball's behavior hascompletelychanged!This isanexampleoftheDecoratorDesignPattern 11 ,wherethe SwitcherStrategy classisformallycalledthe decorator andtheheldstrategyisformallycalledthe decoree .Intheoreticalterms,thedecoratoriswhat isknownasan indirectionlayer ,whichislikeabuerbetweentwoenitiesthatenablesthemtodepend oneachotherbutyetstillbefreetomoveandchangewithrespecttoeachother.Averyusefulanalogy forindirectionlayersislikethethinlayerofoilthatwillenabletwosheetsofmetaltoslideeasilypasteach other. 2.3.3.1.2Ballswithmultiple,compositebehaviors Nowthatwecandynamicallychangeaball'sbehavior,let'stackleanotherproblem: 11 http://www.exciton.cs.rice.edu/JavaResources/DesignPatterns/DecoratorPattern.htm PAGE 38 32 CHAPTER2.POLYMORPHISMINACTION Exercise2.13 Solutiononp.35. Howcanwehaveballswithmultiplebehaviorsbutyetnotduplicatecodeforeachoneofthose behaviors? Let'sstartwithaverystraightforwardsolution: packageballworld; importjava.awt.*; publicclassDoubleStrategyimplementsIUpdateStrategy{ privateIUpdateStrategy_s1=newCurveStrategy; privateIUpdateStrategy_s2=newBreathingStrategy; publicvoidupdateStateBallcontext{ _s1.updateStatecontext; _s2.updateStatecontext; } } Tada!Noproblem.The DoubleStrategy simplyholdstwostrategiesanddelegatestoeachoftheminturn whenaskedto updateState .Sowhystophere? packageballworld; importjava.awt.*; publicclassTripleStrategyimplementsIUpdateStrategy{ privateIUpdateStrategy_s1=newCurveStrategy; privateIUpdateStrategy_s2=newBreathingStrategy; privateIUpdateStrategy_s3=newBreathingStrategy; publicvoidupdateStateBallcontext{ _s1.updateStatecontext; _s2.updateStatecontext; _s3.updateStatecontext; } } We'reonarollnow!Wecouldgoonandon,makingascomplexastrategyaswe'dlike,makinganew classforeachcombinationwewant.Butsomewherearoundthe439'thcombination,wegetmightlytiredof writingclasses.Isn'tthereaneasierway? Abstractionisthekeyhere.Wewanttowritecodethatrepresentsthatabstractionofmultiple,composite strategies.Doeswhatweweredoingabovedependontheparticularconcretestrategiesthatwewereusing? No?Thenweshouldeliminatetheconcreteclasses,raisetheabstractionlevelandusetheabstractsuperclass interfaceinstead.Foracombinationoftwobehaviors,weendupwiththefollowing: packageballworld; importjava.awt.*; publicclassMultiStrategyimplementsIUpdateStrategy{ PAGE 39 33 privateIUpdateStrategy_s1; privateIUpdateStrategy_s2; publicMultiStrategyIUpdateStrategys1,IUpdateStrategys2{ _s1=s1; _s2=s2; } publicvoidupdateStateBallcontext{ _s1.updateStatecontext; _s2.updateStatecontext; } } Noticehowwehaveaddedaconstructorthatenablesustoinitializethetwoabstractstrategyelds.Allwe havetodoistoconstructa MultiStrategy objectwiththetwodesiredstrategies,andwe'regoodtogo! Exercise2.14 Solutiononp.35. Soifwewantthreebehaviors,allwehavetodoistomakethesamesortofthingbutwith3 abstractstrategyelds,right? Thus,withjusta Multistrategy wearecapableofcomposingarbitrarilycomplexbehaviors! 2.3.3.1.3CompositePatterns Sowhathavewewroughthere?Let'stakealookattheUMLdiagramofourtomostabstractstrategies. SwitcherStrategyandMultiStrategy Figure2.8: Notethatthesubclassesholdreferencestotheirownsuperclasses! Thekeytothepowerthatliesinthe SwitcherStrategy andthe MultiStrategy liesinthefactthat theyholdreferencestotheirownsuperclass, IUpdateStrategy .Thisiswhatenablesthemtobecreate anybehaviortheywant,includingcombinationsofbehaviorsanddynamicmodicationsofbehaviors.This PAGE 40 34 CHAPTER2.POLYMORPHISMINACTION self-referentialclassstructureisknownastheCompositeDesignPattern 12 TheDecoratorpatterncanbe consideredtobespecializedformoftheCompositepattern.Themassivepower,exibilityandextensiblility thatthispatterngenerateswarrantsfurther,moreformalstudy,whichiswherewe'reheadingnext.Stay tuned! 12 http://www.exciton.cs.rice.edu/JavaResources/DesignPatterns/composite.htm PAGE 41 35 SolutionstoExercisesinChapter2 SolutiontoExercise2.1p.21 No,itwon'tcompile. IBinaryOp isaninterfaceanddoesnotspecifyanyactualexecutablecode,soit cannotbeinstantiated. SolutiontoExercise2.2p.21 Yes! AddOp isanconcreteclassandcanbeinstantiated. AddOp isan IBinaryOp technically, AddOp implements the IBinaryOp interface,so bop canreferenceit. SolutiontoExercise2.3p.21 Yes,forthesamereasonsasthepreviousexercise! MultOp isanconcreteclassandcanbeinstantiated. MultOp isan IBinaryOp ,so bop canreferenceit. SolutiontoExercise2.4p.21 Theresultis8because bop referstoan AddOp instance,whose apply methodaddsitstwoinputvalues. SolutiontoExercise2.5p.21 Theresultis15because bop nowreferstoan MultOp instance,whose apply methodmultipliesitstwoinput values. SolutiontoExercise2.6p.21 Itisimpossibletotellbecauseitdependsontheexacttypeoftheobjectinstancetowhich myOp refers. SolutiontoExercise2.7p.21 No,because bop isavariableoftype IBinaryOp ,whichisnotdenedashavinga getDescription method.ThisistrueevenifbopreferencesanobjectoftypeMultOp.Thisisbecausethe statictyping of bop tellsthecompilerthatitreferencesan IBinaryOp ,nottheparticularconcretetypeoftheobject itcurrentlyreferences.Ifwehad MultOpmop=newMultOp ,then mop.getDescription isperfectly legal. SolutiontoExercise2.8p.21 Yes,because aop isavariableoftype AddOp ,andthuscanreferenceaninstanceofthesametype. SolutiontoExercise2.9p.21 No,because aop isavariableoftype AddOp ,and MultIOp isnotan AddOp ,so aop cannotreferencean instanceof MultOp SolutiontoExercise2.10p.21 Yes! bop isavariableoftype IBinaryOp ,and aop isdenedasreferencingan AddOp object,whichisan IBinaryOp SolutiontoExercise2.11p.21 Notaswritten,because bop isavariableoftype IBinaryOp i.e.staticlytypedassuch,whichanddoes notnecessarilyreferenceanobjectoftype AddOp .towhich aop mustreference.Thatis,avariableofthe typeofthesuperclascanalwaysreferenceanobjectofthetypeofanysubclass,butavariableofthetype ofaparticularsubclasscannotnecessarilyreferencesomethingofthetypeofitssuperclass.Anotherway ofsayingthisisthatasupersetcontainsitssubsetsbutnottheotherwayaround.Theaboveassignment willcauseacompiletimeerrorbecausethecompilercannotknowiftheassignmentispossible.Anexplicit castisrequiredtosupressthecompiletimeerror aop=AddOpbop ,butmaytriggerarun-timeerrorif indeedtheinstancereferredtoby bop isnotoftype AddOp SolutiontoExercise2.12p.31 Tryit! SolutiontoExercise2.13p.31 Usethesametechniquesasbefore:strategiesthatholdstrategies. SolutiontoExercise2.14p.33 Butisn'ta MultiStrategy an IUpdateStrategy iteself?Thatis,sincea MultiStrategy holds IUpdateStrategy 's,couldn'ta Multistrategy holda Multistrategy ,whichisholdinga Multistrategy ortwowhichisholda Multistrategy ,whichisholding.....? PAGE 42 36 CHAPTER2.POLYMORPHISMINACTION PAGE 43 Chapter3 ImmutableListStructure 3.1ListStructureandtheCompositeDesignPattern 1 3.1.1GoingShopping BeforeIgotothegroceriesstore,ImakealistofwhatIwanttobuy.NotehowIbuildmyshoppinglist:I startwithablanksheetofpaperthenIaddoneitematatime. WhenIgettothestore,Istartbuyingthingsbygoingdownmylist.ForeachitemIbuy,Imarkito thelist. AfterIamdoneshopping,Igotothecashierandcheckoutmyitems. Thecashierscansmyitemsoneitematatime.Eachtime,thecashregisterprintsonelineshowingthe itemjustscannedtogetherwithitsprice.Again,notehowthecashregisterbuildsthelist:itstartwitha blanksheetofpaperandthenaddoneitematatime.Afterallitemshavebeenscanned,thecashierpress akeyand"poof",thecashregisterprintsasubtotal,thenataxamountforallthetaxableitems,thena totalamount,andnallyatotalnumberofitemsbought. Atdierentstore,thecashregisternotonlyprintsoutalloftheabove,butalsoatotalamountof "savings"duetothefactthatIhavea"member-plus"card.Someotherstoresdon'tcaretoprintthetotal numberofitemsboughtatall.Whateverthestore,whereverIgo,Isee"lists"and"listprocessing"allover. Thecheckoutcashregisterusesaprogramtoentertheitemsandprintthereceipt.Attheheartof theprogramisacontainerstructuretoholddatadatastructureandafewalgorithmstomanipulatethe structureandthedataitholds.Thesimplestwaytoorganizedataistostructuretheminalinearfashion; thatis,intuitively,ifwecangetholdofonedataelement,thenthereisexactlyonewaytogettothenext element,ifany.Wecallthislinearorganizationofdatatheliststructure.Inordertowriteprogramto processlists,itisnecessarytodenewhatlistsareandexpresstheirdenitionsintermsofcode. 3.1.2Whatisalist? Analogoustothenotionofashape,alistisanabstractnotion.RecallhowIbuiltmylistofgroceriesitems? Istartedwithablanklist:anemptylist!Theemptyset! Anemptylistisalistthathasnoelement. Itisobviousthattherearenon-emptylists.Butwhatdowemeanbyanon-emptylist?Howcanwe articulatesuchanobviousnotion?Considerforexamplethefollowinglistconsistingofthreeelements. milk bread 1 Thiscontentisavailableonlineat PAGE 44 38 CHAPTER3.IMMUTABLELISTSTRUCTURE butter Intheabove,weorganizetheitemsinalinearfashionwithmilkbeingtherstelement,breadbeingthenext elementfollowingmilkandbutterbeingthenextelementfollowingbread.Isthereanyitemthatfollows butter? Is bread butter alist? Is butter alist? Istherealistthatfollowsbutterintheabove? Anon-emptylistisalistthathasanelementcalledrstandalistcalledrest. Notethatintheaboveformulation,therestofalistisitselfalist!Thedenitionofalistisanexample ofwhatwecalla recursive denition:thelistcontainsasubstructurethatis isomorphic toitself. 3.1.3ListDesignandtheCompositeDesignPattern TheUMLdiagrambelowcapturestherecursivedatadenitionofthelistdatastructure. PAGE 45 39 UMLdiagramofalist Figure3.1: Alistcanberepresentedusingthecompositedesignpattern ThisdenitiontranslatesintoJavacodeasfollows. /***Representstheabstractliststructure.*/publicinterfaceIList{} /** *Representsemptylists. */ publicclassMTListimplementsIList{ } /** *Representsnon-emptylists. */ publicclassNEListimplementsIList{ privateObject_first; privateIList_rest; } PAGE 46 40 CHAPTER3.IMMUTABLELISTSTRUCTURE Table3.1 Theaboveisanexampleofwhatiscalledthe compositedesignpattern .Thecompositepatternisa structural patternthatprescribeshowtobuildacontainerobjectthatiscomposedofotherobjectswhose structuresare isomorphic tothatofthecontaineritself.Inthispattern,thecontaineriscalledacomposite. Intheabove,IListiscalledtheabstractcomponent,MTListiscalledthebasiccomponentandNEListis calledthecomposite.Thecompositedesignpatternembodiestheconceptof recursion ,oneofthemost powerfulthinkingtoolincomputing.Thereisasubjectintheoreticalcomputerscienceandmathematics called"recursivefunctiontheory,"whichstudiesthemeaningofwhatcomputingmeansandineectdenes inthemostabstractformwhatacomputerisandwhatitcanandcannotdo. 3.1.4ListCreation Nowthatwehavedenedwhatalistis,weaskourselveshowwecanprocessit?Whatcanwedowitha list?Theabovecodemakesitclearthatthereisnotawholelotwecandowithalistbesidesinstantiating abunchofMTListobjectsviathecallnewMTListwhy?.NowthatweareusingthefullJavalanguage, weneedtowriteaconstructorforNEListinordertoinstantiatenon-emptylistobjectswithappropriate rstandrest.TheJavacodeforNEListnowlooksasfollowsnotehowthecommentsarewritten. /** *Representsnon-emptylists. */ publicclassNEListimplementsIList{ privateObject_first; privateIList_rest; /** *InitializesthisNEListtoagivenfirstandagivenrest. *@paramfthefirstelementofthisNEList. *@paramrtherestofthisNEList. */ publicNEListObjectf,IListr{ _first=f; _rest=r; } } Theliststructureascodedintheaboveiscompletely encapsulated ,thatis,allinternalcomponentsif anyofalistareprivateandcannotbeaccessedbyanyexternalcode.Usingtheappropriateconstructors, wecanmakeabunchofliststostoredatabutwecannotretrievedatanordoanythingwiththeselists.In Object-OrientedProgrammingOOPparlance,thelistissaidtohavenobehavioratall.Assuchtheyare ofnousetous. 3.1.5ListProcessing Inordertoperformanymeaningfullistprocessingatall,weneedtoprogrammore"intelligence"intothelist structurebyaddingappropriatemethodstothelisttoprovidethedesiredbehaviors.Soinsteadofasking whatwecandowithalist,therightquestiontoaskinOOPis"whatcanalistdoforus?"Letusstartby presentingafewsimpletasksthatwewantalisttoperformandtrytogureouthowan"intelligent"list wouldcarryoutsuchtasksviasomeroleacting. PAGE 47 41 3.1.5.1Inclassrole-actingexercises: Computethelengthofalist. Computethesumofalistthatholdsintegers. 3.2ListStructureandtheInterpreterDesignPattern 2 3.2.1ListProcessing Inthepreviouslecture,wedenewhatalistisandimplementitusingthecompositedesignpattern.Thislist structureisfullyencapsulatedanddoesnotexposeanyofitsinternalcomponents.Inordertomanipulate suchalistwithouthavingtomakepublicitsinternals,weneedtoaddmethodstothestructure.Thislecture discussesthestructureofthealgorithmsonthelist. 3.2.1.1Whatcanalistdo? 3.2.1.1.1Lengthofalist SupposewearegivenalistLandaskedtondouthowmanyelementsithas.Whatshouldwedo?The temptationhereistostartthinkingabout"traversing"thelistandkeepacountaswegoalong,andwhen weencounterthe"end"ofthelist,thecountshouldbethenumberofelementsinthelist.Buthowdowe knowthatthat'stherightanswer?Inordertodeterminewhetherornottheresultobtainedbycountingas onetraversesthelistfrombeginningtoendiscorrect,wehavetodenewhatitmeanstobethenumberof elementsinthelist.Thenumberofelementsinalistisanabstractnotion,isn'tit?Inordertodenesuch aquantity,weneedtogobacktothedenitionofwhatalistis. A list isan abstract notionofacontainerstructure. Anemptylistisa list thathasnoelement Anon-emptylistisa list thathasanelementcalledrstanda list calledrest. Todenethenotionofthenumberofelementsinalist,weneedtodenewhatwemeanbythenumberof elementsinanemptylistandwhatwemeanbythenumberofelementsinanon-emptylist. Thenumberofelementsinalistisanabstractnotionbecausethelistisanabstractnotion. Thenumberofelementsofanemptylistis0. Thenumberofelementsinanon-emptylistthatcontainsrstandrestis1plusthenumberofelements inrest. Thedenitionofthenumberofelementsinalististhusrecursive.Therecursivecharacteristicofthis denitionarisesnaturallyfromtherecursivecharacteristicoftheliststructure.Whateverapproachweuse tocomputethenumberofelementsinalist,inordertoprovecorrectness,wemustshowthattheresult satisestheabovedenition. Hereisthecodefortheabovecomputation. 2 Thiscontentisavailableonlineat PAGE 48 42 CHAPTER3.IMMUTABLELISTSTRUCTURE packagelistFW;/***Representstheabstractliststructure.*/publicinterface IList{/***AbstractnotionofthenumberofelementsinthisIList.*/publicint getLength;} packagelistFW; /** *Representsemptylists. */ publicclassMTListimplementsIList{ /** *Thenumberofelementsinanemptylistiszero. */ publicintgetLength{ return0; } } packagelistFW; /** *Representsnon-emptylists. */ publicclassNEListimplementsIList{ privateObject_first; privateIList_rest; //Constructorommitted. /** *Thenumberofelementsinanon-emptylistis *thenumberofelementsofitsrestplus1. */ publicintgetLength{ return1+_rest.getLength; } } continuedonnextpage PAGE 49 43 Table3.2 Theabovecodingpatternisanexampleofwhatiscalledthe interpreterdesignpattern :weareinterpretingtheabstractbehaviorofaclassorinterfaceineachoftheconcretesubclassesorimplementations. Thecompositepatternisapatterntoexpressthestructureofasystem,whiletheinterpreterpatternisused toexpressthebehaviorsi.e.methodsofthesystem.Theinterpreterpatternisusuallyappliedtocoding methodsinacompositestructure.Inalaterlecture,weshallseeanotherwayofexpressingthebehaviorof acompositestructurewithouthavingtoaddnewmethodsandinterpretthem. 3.2.1.2CodeTemplate WheneverwewanttheIListtoperformatask,weaddamethodtoIListandwriteappropriateconcrete implementationsinMTListandNEList.Thefollowingtableillustratesthecodetemplateforwritingthe concretecodeinMTListandNEList. interfaceIList publicabstractreturnTypemethodNameparameterlist;//returnTypemaybe'void' MTList //nodata NEList Object_first; IList_rest; publicreturnTypemethodNameparameterlist{ /* Thisisingeneralthebasecaseofarecursivecall. Writethenon-recursivecodetosolvetheproblem. */ } publicreturnTypemethodNameparameterlist{ /* Thisisingeneralarecursivemethod. Thecodeherecanreferto_firstand_rest,andallthemethodsinNEList Whenreferencing_rest,oneusuallymakestherecursivecall: _rest.methodNameappropriateparameters. */ } continuedonnextpage PAGE 50 44 CHAPTER3.IMMUTABLELISTSTRUCTURE Table3.3 3.2.1.2.1InClassExercisesRole-Acting Findanumberinalistandreturn"Foundit!"ifthenumberisinthelistotherwisereturn"Notfound!" AppendalistBtoagivenlistAandreturnanewlistconsistingofAandBconcatenatedtogether. 3.3VisitorDesignPattern 3 3.3.11.DecouplingAlgorithmsfromDataStructures Recallthecurrentformulationoftheimmutableliststructureusingthecompositepattern. 3 Thiscontentisavailableonlineat PAGE 51 45 Figure3.2 Eachtimewewanttocomputesomethingnew,weapplytheinterpreterpatternaddappropriatemethods toIListandimplementthosemethodsinMTListandNEList.Thisprocessofextendingthecapabilityof theliststructureiserror-proneatbestandcannotbecarriedoutifonedoesnotownthesourcecodeforthis structure.AnymethodaddedtothesystemcanaccesstheprivateeldsofMTListandNEListandmodify thematwill.Inparticular,thecodecanchange_stand_restofNEListbreakingtheinvariantimmutable propertythesystemissupposedtorepresent.Thesystemsodesignedisinherentlyfragile,cumbersome, rigid,andlimited.WeendupwithaforeverchangingIListthatincludesamultitudeofunrelatedmethods. Thesedesignawscomeofthelackofdelineationbetweentheintrinsicandprimitivebehaviorofthe structureitselfandthemorecomplexbehaviorneededforaspecicapplication.Thefailuretodecouple PAGE 52 46 CHAPTER3.IMMUTABLELISTSTRUCTURE primitiveandnon-primitiveoperationsalsocausesreusabilityandextensibilityproblems.Theweakness inbundlingadatastructurewithapredenedsetofoperationsisthatitpresentsastaticnon-extensible interfacetotheclientthatcannothandleunforeseenfuturerequirements.Reusabilityandextensibility aremorethanjustaestheticissues;intherealworld,theyaredrivenbypowerfulpracticalandeconomic considerations.Computersciencestudentsshouldbeconditionedtodesigncodewiththeknowledgethatit willbemodiedmanytimes.Inparticularistheneedfortheabilitytoaddfeaturesafterthesoftwarehas beendelivered.Thereforeonemustseektodecouplethedatastructuresfromthealgorithmsoroperations thatmanipulateit.Beforewepresentanobject-orientedapproachtoaddressthisissue,let'srsteat! 3.3.22.ToCookorNotToCook Maryisavegetarian.Sheonlycooksandeatsvegetarianfood.Johniscarnivorous.Hecooksandeats meat!IfMarywantstoeatbroccoliandcheese,shecanlearnhowtocookbroccoliandcheese.Ifshe wantscornofthecob,shecanlearnhowtocookcornonthecob.ThesamegoesforJohn.Ifhewantsto eatgreasyhamburger,hecanlearnhowtocookgreasyhamburger.Ifhewantstoeatfattyhotdog,hecan learnhowtocookfattyhotdog.EverytimeJohnandMarywanttoeatsomethingnew,theycanlearnhow tocookit.ThisrequiresthatJohnandMarytoeachhaveaverybigheadinordertolearnalltherecipes. Butwait,therearepeopleouttherecalledchefs!Theseareveryspecialkindsofchefscateringonly tovegetariansandcarnivores.Thesechefsonlyknowhowtocooktwodishes:onevegetariandishand onemeatdish.AllJohnandMaryhavetodoistoknowhowtoasksuchacheftocooktheirfavorite dish.Marywillonlyorderthevegetariandish,whileJohnwillonlyorderthemeatdish! Howdowemodelthevegetarian,thecarnivore,thechef,thetwokindsofdishesthechefcooks,andhow thecustomerorderstheappropriatekindofdishfromthechef? 3.3.2.1TheFood Tosimplifytheproblem,let'streatfoodasString.Inamoresophisticatedsetting,wemaywantto modelfoodassomeinterfacewithveggieandmeatassub-interface. 3.3.2.2TheFoodConsumers Vegetariansandcarnivoresarebasicallythesameanimals.Theyhavethebasicingredientssuchassaltand peppertocookfood.Theydierinthekindofrawmaterialstheystocktocooktheirfoodsandintheway theyorderfoodfromachef.VegetariansandCarnivorescanprovidethematerialstocookbutdonotknow howtocook!Inordertogetanycookedmeal,theyhavetoaskacheftocookforthem.Wemodelthemas twoconcretesubclassesofan abstractclass called AEater AEater hastwoconcretemethods, getSalt and getPepper ,andan abstract methodcalled order ,asshowninthetablebelow. publicabstractclassAEater{publicStringgetSalt{return"salt";}publicString getPepper{return"pepper";}/***Ordersnportionsofappropriatefoodfrom restaurantr.*/publicabstractStringorderIChefr,Integern;//NOCODEBODY! } continuedonnextpage PAGE 53 47 publicclassVegetarianextendsAEater{ publicStringgetBroccoli{ return"broccoli"; } publicStringgetCorn{ return"corn"; } publicStringorderIChefc,Objectn{ //codetobediscussedlater; } } publicclassCarnivoreextendsAEater{ publicStringgetMeat{ return"steak"; } publicStringgetChicken{ return"cornishhen"; } publicStringgetDog{ return"polishsausage"; } publicStringorderIChefc,Objectn{ //codetobediscussedlater; } } Table3.4 3.3.2.3TheChef ThechefisrepresentedasaninterfaceIChefwithtwomethods,onetocookavegetariandishandoneto cookameatdish,asshowninthetablebelow. interfaceIChef{StringcookVeggieVegetarianh,Integern;StringcookMeatCarnivore h,Integern;} publicclassChefWongimplementsIChef{ publicstaticfinalChefWongSingleton =newChefWong; privateChefWong{} publicStringcookVeggieVegetarianh,Integern{ returnn+"portionsof"+ h.getCarrot+","+ h.getSalt; } publicStringcookMeatCarnivoreh,Integern{ returnn+"portionsof"+ h.getMeat+","+ h.getPepper; } } publicclassChefZungimplementsIChef{ publicstaticfinalChefZungSingleton =newChefZung; privateChefZung{} publicStringcookVeggieVegetarianh,Integern{ returnn+"portionsof"+ h.getCorn+","+ h.getSalt; } publicStringcookMeatCarnivoreh,Integern{ returnn+"portionsof"+ h.getChicken+","+ h.getPepper+ ","+h.getSalt; } } Table3.5 PAGE 54 48 CHAPTER3.IMMUTABLELISTSTRUCTURE 3.3.2.4OrderingFoodFromTheChef ToorderfoodfromanIChef,aVegetarianobjectsimplycallscookVeggie,passingitselfasoneoftheparameters,whileaCarnivoreobjectwouldcallcookMeat,passingitselfasoneoftheparametersaswell.The VegetarianandCarnivoreobjectsonlydealwiththeIChefobjectatthehighestlevelofabstractionanddo notcarewhattheconcreteIChefis.Thepolymorphismmachineryguaranteesthatthecorrectmethodin theconcreteIChefwillbecalledandtheappropriatekindoffoodwillbereturnedtotheAEatercallerThe tablebelowshowsthecodeforVegetarianandCarnivore,andsampleclientcodeusingtheseclasses. publicclassVegetarianextendsAEater{ //othermethodselided publicStringorderIChefc,intn{ returnc.cookVeggiethis,n; } } publicclassCarnivoreextendsAEater{ //othermethodselided publicStringorderIChefc,intn{ returnc.cookMeatthis,n; } } //clientcodepublicvoidpartyAEatere,IChefc,intn{System.out.printlne.orderc, n;}//blahblahblah...AEaterJohn=newCarnivore;AEaterMary=new Vegetarian;partyMary,ChefWong.Singleton,2;partyJohn,ChefZung.Singleton,1; Table3.6 Theabovedesignisanexampleofwhatiscalledthevisitorpattern. TheabstractclassAEateranditsconcretesubclassesarecalledthehosts.ThemethodpublicString orderIChefc,Objectniscalledthehookmethod.EachconcretesubclassesofAEaterknowsexactly tocalltheappropriatemethodontheIChefparameter,butdoesknowandneednothowtheIChef concretelyperfornsitstask.Thisallowsanopen-endednumberofwaystocooktheappropriatekinds offood. ThechefinterfaceIChefandallofitsconcreteimplementationsarecalledvisitors.WhenanIChef performscookMeat/cookVeggie,itknowsthatitshostisaCarnivore/Vegetarianandcanonlycallthe methodsofCarnivore/Vegetariantocookadish.Javastatictypecheckingwillaganerrorshould therebeacallonthehosttogetCarotinthemethodcookMeat.Thisismakestheinteractionbetween hostsVegetarianandCarnivoreandvisitorsIChefandallofitsconcreteimplementationsmuch morerobust. 3.3.33.TheVisitorPattern Thevisitorpattern 4 isapatternforcommunicationandcollaborationbetweentwounionpatterns:a"host" unionanda"visitor"union.AnabstractvisitorisusuallydenedasaninterfaceinJava.Ithasa separatemethodforeachoftheconcretevariantofthehostunion.Theabstracthosthasamethodcalled the"hook"to"accept"avisitorandleavesituptoeachofitsconcretevariantstocalltheappropriate visitormethod.This"decoupling"ofthehost'sstructuralbehaviorsfromtheextrinsicalgorithmsonthe hostpermitstheadditionofinnitelymanyexternalalgorithmswithoutchanginganyofthehostunion 4 http://www.exciton.cs.rice.edu/JavaResources/DesignPatterns/VisitorPattern.htm PAGE 55 49 code.Thisextensibilityonlyworksifthetaxonomyofthehostunionisstableanddoesnotchange.Ifwe havetomodifythehostunion,thenwewillhavetomodifyALLvisitorsaswell! PAGE 56 50 CHAPTER3.IMMUTABLELISTSTRUCTURE Figure3.3 PAGE 57 51 NOTE:Allthe"state-less"visitors,thatisvisitorsthatcontainnonon-staticeldsshouldbesingletons.Visitorsthatcontainnon-staticeldsshouldnotbesingletons. 3.3.44.FundamentalObject-OrientedDesignMethodologyFOODM 1. Identifyandseparatethevariantandtheinvariantbehaviors. 2. Encapsulatetheinvariantbehaviorsintoasystemofclasses. 3. Add"hooks"tothisclasstodenecommunicationprotocolswithotherclasses. 4. Encapsulatethevariantbehaviorsintoaunionofclassesthatcomplywiththeabove protocols. Theresultisaexiblesystemofco-operatingobjectsthatisnotonlyreusableandextensible,butalsoeasy tounderstandandmaintain. Letusillustratetheaboveprocessbyapplyingittothedesignoftheimmutableliststructureandits algorithms. 1.Here,theinvariantistheintrinsicandprimitivebehavioroftheliststructure, IList ,andthevariants arethemultitudeofextrinsicandnon-primitivealgorithmsthatmanipulateit, IListAlgo 2.Therecursiveliststructureisimplementedusingthecompositedesignpatternandencapsulatedwith aminimalandcompletesetofprimitivestructuraloperations: getFirst and getRest 3.Thehookmethod ObjectexecuteIListAlgoago,Objectinp denestheprotocolsforoperatingontheliststructure.Thehookworksasifa IList announcestotheoutsideworldthefollowing protocol: Ifyouwantmetoexecuteyouralgorithm,encapsulateitintoanobjectoftypeIListAlgo, handittometogetherwithitsinpobjectasparametersformyexecute.Iwillsendyouralgorithm objecttheappropriatemessageforittoperformitstask,andreturnyoutheresult. emptyCase... shouldbethepartofthealgorithmthatdealswiththecasewhereIamempty. nonEmptyCase... shouldbethepartofthealgorithmthatdealswiththecasewhereIamnot empty. 4. IListAlgo andallofitsconcreteimplementationsformsaunionofalgorithmsclassesthatcanbesent totheliststructureforexecution. BelowistheUMLclassdiagramoftheresultinglistdesign.Clickheretoseethefulldocumentation. 5 Clickheretoseethecode 6 5 http://www.owlnet.rice.edu/ comp201/08-spring/lectures/visitor/listFW/doc/ 6 http://www.owlnet.rice.edu/ comp201/08-spring/lectures/lec17/listFW.zip PAGE 58 52 CHAPTER3.IMMUTABLELISTSTRUCTURE Figure3.4 Theabovedesignisnothingbutaspecialcaseofthe VisitorPattern .Theinterface IList iscalled the host anditsmethod execute iscalleda" hook "tothe IListAlgo visitors .Viapolymorphism, IList knowsexactlywhatmethodtocallonthespecic IListAlgo visitor.Thisdesignturnsthelist structureintoaminiatureframeworkwherecontrolisinverted:onehandsanalgorithmtothestructureto beexecutedinsteadofhandingastructuretoanalgorithmtoperformacomputation.Sincean IListAlgo onlyinteractswiththelistonwhichitoperatesviathelist'spublicinterface,theliststructureiscapableof carryingoutanyconformingalgorithm,past,present,orfuture.Thisishowreusabilityandextensibilityis achieved. 3.3.55.ListVisitorExamples PAGE 59 53 /***ComputesthelengthoftheIListhost.*/publicclassGetLengthimplements IListAlgo{/***SingletonPattern.*/publicstaticfinalGetLengthSingleton=new GetLength;privateGetLength{} /** *ReturnsInteger. *@paramnunotused *@returnInteger */ publicObjectemptyCaseMTListhost,Object...nu{ return0; } /** *Returnthelengthofthehost'srestplus1. *@paramnunotused. *@returnInteger > 0. */ publicObjectnonEmptyCaseNEListhost,Object...nu{ ObjectrestLen=host.getRest.executethis; return1+IntegerrestLen; } Table3.7 packagelistFW;/***ComputesaStringreprsentationofIListshowingaleft parenthesisfollowed*byelementsoftheIListseparatedbycommas,endingwithwith arightparenthesis.*@stereotypevisitor*/publicclassToStringAlgoimplements IListAlgo{publicstaticfinalToStringAlgoSingleton=newToStringAlgo;private ToStringAlgo{} /** *Returns"". */ publicObjectemptyCaseMTListhost,Object...inp{ return""; } /** *Passes""+firsttotherestofIListandasksforhelptocompletethecomputation. */ publicObjectnonEmptyCaseNEListhost,Object...~inp{ returnhost.getRest.executeToStringHelper.Singleton,""+host.getFirst; } } Table3.8 PAGE 60 54 CHAPTER3.IMMUTABLELISTSTRUCTURE /***HelpsToStringAlgocomputetheStringrepresentationoftherestofthelist. */classToStringHelperimplementsIListAlgo{publicstaticfinalToStringHelper Singleton=newToStringHelper;privateToStringHelper{} /** ~*ReturnstheaccumulatedString+"". ~*Atendoflist:done! ~*/ publicObjectemptyCaseMTListhost,Object...acc{ return~acc[0]+""; } /** *ContinuesaccumulatingtheStringrepresentationbyappending","+firsttoacc *andrecurse! */ publicObjectnonEmptyCaseNEListhost,Object...acc{ returnhost.getRest.executethis,acc[0]+","+host.getFirst; } } Table3.9 WenowcanusetoToStringAlgotoimplementthetoStringmethodofanIList. PAGE 61 55 packagelistFW; publicclassMTListimplementsIList{ /** *SingletonPattern */ publicfinalstaticMTListSingleton=newMTList; privateMTList{} /** *Callstheemptycaseofthealgorithmalgo, *passingtoititselfasthehostparameter *andthegiveninputinpastheinputparameter. *Thismethodismarkedasfinaltopreventall *subclassesfromoverridingit. *Finalizingamethodalsoallowsthecompilerto *generatemoreefficientcallingcode. */ publicfinalObjectexecuteIListAlgoalgo,Object...inp{ returnalgo.emptyCasethis,inp; } publicStringtoString{ returnStringToStringAlgo.Singleton.emptyCasethis; } } packagelistFW; publicclassNEListimplementsIList{ /** *Thefirstdataelement. */ privateObject_first; /** *Therestor"tail"ofthisNEList. *DataInvariant:_rest!=null; */ privateIList_rest; /** *InitializesthisNEListtoagivenfirstandagivenrest. *@paramfthefirstelementofthisNEList. *@paramr!=null,therestofthisNEList. */ publicNEListObjectf,IListr{ _first=f; _rest=r; } /** *ReturnsthefirstdataelementofthisNEList. *Thismethodismarkedasfinaltopreventallsubclasses *fromoverridingit. *Finalizingamethodalsoallowsthecompilertogenerate *moreefficientcallingcode. */ publicfinalObjectgetFirst{ return_first; } /** *ReturnsthefirstdataelementofthisNEList. *Thismethodismarkedasfinaltopreventall *subclassesfromoverridingit. *Finalizingamethodalsoallowsthecompiler *togeneratemoreefficientcallingcode. */ publicfinalIListgetRest{ return_rest; } /** *CallsthenonEmptyCasemethodoftheIListAlgoparameter, *passingtothemethoditselfasthehostparameterandthe *giveninputastheinputparameter. *Thismethodismarkedasfinaltopreventallsubclassesfrom *overridingit.Finalizingamethodalsoallowsthecompiler *togeneratemoreefficientcallingcode. */ publicfinalObjectexecuteIListAlgoalgo,Object...inp{ returnalgo.nonEmptyCasethis,inp; } publicStringtoString{ returnStringToStringAlgo.Singleton.nonEmptyCasethis; } } PAGE 62 56 CHAPTER3.IMMUTABLELISTSTRUCTURE Table3.10 Downloadtheabovecodehere 7 3.4AbstractFactoryDesignPattern 8 3.4.11.InformationHiding Informationhidingisatried-and-truedesignprinciplethatadvocateshidingallimplementationdetailsof softwarecomponentsfromtheuserinordertofacilitatecodemaintenance.ItwasrstformulatedbyDavid L.Parnasin1971-1972asfollows. Onemustprovidetheintendeduserwithalltheinformationneededtousethemodulecorrectly and nothingmore translationtoOOP:theusershouldnotknowanythingabouthowaninterfaceorabstractclass isimplemented.Forexample,theuserneednotandshouldnotknowhow IList isimplemented inordertouseit.Theusershouldonlyprogramtotheabstractspecication. Onemustprovidetheimplementorwithalltheinformationneededtocompletethemoduleandnothing more. translationtoOOP:theimplementorofaclassoraninterfaceshouldnotknowanythingabout howitwillbeused.Forexample,theimplementorneednotandshouldnotknowhow,when,or where IList willbeused.Theimplementorshouldwritetheimplementationcodebasedsolely ontheabstractspecication. Byadheringtotheabove,codewrittenbybothusersandimplementorswillhaveahighdegreeofexibility, extensibility,interoperabilityandinterchangeability. Thelistframeworkthatwehavedevelopedsofarhasfailedtohide MTList and NEList ,whichareconcrete implementationsof IList ,theabstractspecicationoftheliststructure.Inmanyofthelistalgorithmsthat wehavedevelopedsofar,weneedtocallon MTList.Singleton ortheconstructorof NEList toinstantiate concrete IList objects.Thefollowingisanothersuchexamples. 7 http://www.owlnet.rice.edu/ comp201/08-spring/lectures/lec17/listFW.zip 8 Thiscontentisavailableonlineat PAGE 63 57 InsertInOrder.java importlistFW.*; /** *InsertsanIntegerintoanorderedhostlist,assumingthehostlistcontains *onlyIntegerobjects. */ publicclassInsertInOrderimplementsIListAlgo{ publicstaticfinalInsertInOrderSingleton=newInsertInOrder; privateInsertInOrder{ } /** *Thisiseasy,don'tyouthink? *@paraminpinp[0]isanIntegertobeinsertedinorderintohost. */ publicObjectemptyCaseMTListhost,Object...inp{ returnnewNEListinp[0],host; } /** *Delegatetorecur! *@paraminpinp[0]isanIntegertobeinsertedinorderintohost. */ publicObjectnonEmptyCaseNEListhost,Object...inp{ intn=Integerinp[0]; intf=Integerhost.getFirst; returnn < f? newNEListinp[0],host: newNEListhost.getFirst,IListhost.getRest.executethis,inp[0]; } } Table3.11 Theabovealgorithmtoinsertinorderanintegerintoanorderedlistofintegerscanonlybeusedforavery specicimplementationof IList ,namelytheonethathas MTList and NEList asconcretesubclasses.How canwewritelistalgorithmsthatcanbeusedforANYimplementationoftheabstractspecicationofthe liststructurerepresentedbytheabstractclass IList ? Wecanachieveourgoalby 1.abstractingthebehaviorof MTList and NEList intointerfaceswithpureabstractstructuralbehaviors. 2.applyingtheAbstractFactoryDesignPattern 9 tohidetheconcreteimplementationfromtheuser. 9 http://www.exciton.cs.rice.edu/JavaResources/DesignPatterns/FactoryPattern.htm PAGE 64 58 CHAPTER3.IMMUTABLELISTSTRUCTURE 3.4.22.AbstractListBehaviors Theconcreteemptylistandnon-emptylistimplementedas MTList and NEList arenowexpressedas interfacesasfollow. packagelistFW;/***Representstheabstractbehavioroftheimmutableliststructure. *Alistintrinsically"knows"howtoexecuteanalgorithmonitself.*/interface IList{ObjectexecuteIListAlgoalgo,Object...inp;} packagelistFW; /** *Representstheimmutableemptylist. *Theemptylisthasnowell-definedstructuralbehavior: *ithasnofirstandnorest. */ interfaceIMTListextendsIList{ } packagelistFW; /** *Representstheimmutablenon-emptylist. *Animmutablenon-emptylisthasadataobjectcalledfirst,andan *isomorphicsubcomponentcalledrest.Itsstructuralbehavior *providesaccesstoitsinternaldatafirstandsubstructurerest. */ interfaceINEListextendsIList{ /** *"Gettor"methodforthelist'sfirst. *@returnthisINElist'sfirstelement. */ ObjectgetFirst; /** *"Gettor"methodforthelist'srest. *@returnthisINElist'srest. */ IListgetRest; } Table3.12 3.4.33.AbstractListFactory Beforewedescribeingeneralwhatthe AbstractFactoryPattern is,let'sexaminewhatwehavetodo inthecaseof IList Deneanabstractfactoryinterface, IListFactory ,tomanufactureemptyandnon-empty IList objects.Put IList IMTList INEList IListVistor ,and IListFactory inthesamepackage. IListFactory isspeciedasfollowed. PAGE 65 59 IListFactory.java packagelistFW; /** *AbstractfactorytomanufactureIMTListandINEList. */ interfaceIListFactory{ /** *Createsanemptylist. *@returnanIMTListobject. */ IMTListmakeEmptyList; /** *Createsanon-emptylistcontainingagivenfirstandagivenrest. *@paramfirstadataobject. *@paramrest!=null,therestofthenon-emptylisttobemanufactured. *@returnanINEListobjectcontainingfirstandrest *@exceptionIllegalArgumentExceptionifrestisnull. */ INEListmakeNEListObjectfirst,IListrest; } Table3.13 IList IListAlgo ,and IListFactory prescribea minimal and complete abstractspecicationofwhat wecallalist softwarecomponent .Weclaimwithoutproofthatwecandoeverythingweeverwantto dowiththeliststructureusingthisspecication. Allalgorithmsi.e.visitorsthatcallforthecreationofconcrete IList objectswillneedtohavean abstractfactoryasaparameteranduseittomanufacture IList objects.Weusuallypassthefactory asanargumenttotheconstructorofthevisitor.Thevisitoristhusnotasingleton. PAGE 66 60 CHAPTER3.IMMUTABLELISTSTRUCTURE InsertInOrderWithFactory.java importlistFW.*; /** *InsertsanIntegerintoanorderedhostlist,assumingthehostlistcontains *onlyIntegerobjects.HasnoknowledgeofhowIListisimplemented.Must *makeuseofalistfactoryIListFactorytocreateIListobjectsinsteadof *callingtheconstructorsofconcretesubclassesdirectly. */ publicclassInsertInOrderWithFactoryimplementsIListAlgo{ privateIListFactory_listFact; publicInsertInOrderWithFactoryIListFactorylf{ _listFact=lf; } /** *Simplymakesanewnon-emptylistwiththegiveninpparameterasfirst. *@paramhostanemptyIList. *@paraminpinp[0]isanIntegertobeinsertedinorderintohost. */ publicObjectemptyCaseIMTListhost,Object...inp{ return_listFact.makeNEListinp[0],host; } /** *Recur! *@paramhostanon-emptyIList. *@paraminpinp[0]isanIntegertobeinsertedinorderintohost. */ publicObjectnonEmptyCaseINEListhost,Object...inp{ intn=Integerinp[0]; intf=Integerhost.getFirst; returnn < f? _listFact.makeNEListinp[0],host: _listFact.makeNEListhost.getFirst, IListhost.getRest.executethis,inp[0]; } } Table3.14 Theabovealgorithmonly"talks"totheliststructureitoperatesonatthehighestlevelofabstraction speciedby IList and IListFactory .Itdoesknowanddoesnotcarehow IList and IListFactory are implemented.Yetitcanbeprovedtobecorrect.Thisalgorithmcanbepluggedintoanysystemthat subscribestotheabstractspecicationprescribedby IList IListAlgo ,and IListFactory . PAGE 67 61 Provideaconcreteimplementationoftheabstractfactorythatcontainsallconcretesubclassesof IList as privatestatic classesandthushidethemfromallexternalcode. PAGE 68 62 CHAPTER3.IMMUTABLELISTSTRUCTURE CompositeListFactory.java packagelistFW.factory; importlistFW.*; /** *ManufacturesconcreteIMTListandINEListobjects.Hasonlyone *instancereferencedbyCompositeListFactory.Singleton. *MTListandNEListarestaticnestedclassesandhiddenfromallexternal *clientcode.TheimplementationsforMTListandNEListarethesameas *beforebutcompletelyinvisibletotheoutsideofthisfactory. */ publicclassCompositeListFactoryimplementsIListFactory{ /** *Notetheuseofprivatestatic. */ privatestaticclassMTListimplementsIMTList{ publicfinalstaticMTListSingleton=newMTList; privateMTList{ } finalpublicObjectexecuteIListAlgoalgo,Object...inp{ returnalgo.emptyCasethis,inp; } publicStringtoString{ return""; } } /** *Notetheuseofprivatestatic. */ privatestaticclassNEListimplementsINEList{ privateObject_first; privateIList_rest; publicNEListObjectdat,IListrest{ _first=dat; _rest=rest; } finalpublicObjectgetFirst{ return_first; } finalpublicIListgetRest{ return_rest; } finalpublicObjectexecuteIListAlgoalgo,Object...inp{ returnalgo.nonEmptyCasethis,inp; } publicStringtoString{ returnStringToStringAlgo.Singleton.nonEmptyCasethis; } } /** *SingletonPattern */ publicstaticfinalCompositeListFactorySingleton=newCompositeListFactory; privateCompositeListFactory{ } /** *Createsanemptylist. *@returnanIMTListobject. */ publicIMTListmakeEmptyList{ returnMTList.Singleton; } /** *Createsanon-emptylistcontainingagivenfirstandagivenrest. *@paramfirstadataobject. *@paramrest!=null,therestofthenon-emptylisttobemanufactured. *@returnanINEListobjectcontainingfirstandrest */ publicINEListmakeNEListObjectfirst,IListrest{ returnnewNEListfirst,rest; } } PAGE 69 63 Table3.15 Passsuchaconcretefactorytoallclientcodethatneedtomakeuseoftheabstractfactorytomanufactureconcrete IList instances. Belowisanexampleofaunittestforthe InsertInOrderWithFactory algorithm. Test_InsertInOrderWithFactory.java packagelistFW.visitor.test; importlistFW.*; importlistFW.factory.*; importlistFW.visitor.*; importjunit.framework.TestCase; /** *AJUnittestcaseclass. *Everymethodstartingwiththeword"test"willbecalledwhenrunning *thetestwithJUnit. */ publicclassTest_InsertInOrderWithFactoryextendsTestCase{ publicvoidtest_ordered_insert{ IListFactoryfac=CompositeListFactory.Singleton; IListAlgoalgo=newInsertInOrderWithFactoryfac; IListlist0=fac.makeEmptyList; assertEquals"Emptylist","",list0.toString; IListlist1=IListlist0.executealgo,55; assertEquals"55> ","",list1.toString; IListlist2=IListlist1.executealgo,30; assertEquals"30> ",",55",list2.toString; IListlist3=IListlist2.executealgo,100; assertEquals"100> ,55",",55,100",list3.toString; IListlist4=IListlist3.executealgo,45; assertEquals"45> ,55,100",",45,55,100",list4.toString; IListlist5=IListlist4.executealgo,60; assertEquals"60> ,45,55,100",",45,55,60,100",list5.toString; } } Table3.16 PAGE 70 64 CHAPTER3.IMMUTABLELISTSTRUCTURE Theabovedesignprocessisanexampleofwhatiscalledthe AbstractFactoryDesignPattern .The intentofthispatternistoprovideanabstractspecicationformanufacturingafamilyofrelatedobjects forexamples,theemptyandnon-empty IList withoutspecifyingtheiractualconcreteclassesthushiding alldetailsofimplementationfromtheuser. Ourexampleoftheliststructureframeworksuccessfullydelineatesspecicationfromimplementation andfaithfullyadherestotheprincipleofinformationhiding. IList IMTList INEList IListAlgo ,and IListFactory provideaminimalandcompleteabstract specication. InsertInOrderWithFactory isaconcreteimplementationof IListAlgo thatperformsaconcrete operationonthehostlist.Yetthisalgorithmneedonlycommunicatewiththeliststructureandthelist factoryviatheirpublicinterface.Itwillworkwithanyimplementationof IList and IListFactory CompositeListFactory isaconcreteimplementationof IListFactory .Itusesthecompositepattern andthevisitorpatterntoimplement IList .Itonlycommunicateswith IListAlgo atandknows nothingaboutanyofitsconcreteimplementation.The privatestatic attributesprovidetheproper mechanismtohideallimplementationdetailsfromallcodeexternaltotheclass. ClickheretoaccessthecompletejavadocdocumentationandUMLclassdiagramofthelistcomponent 10 describedintheabove. Clickheretodownloadthecompletesourcecodeanddocumentationofthelistcomponent 11 described intheabove. 3.4.44.Frameworks Thefollowingisadirectquotefromthe DesignPatterns bookbyGamma,Helm,Johnson,andVlissides theGangofFour-GoF. Frameworksthusemphasizesdesignreuseovercoderesuse...Reuseonthislevelleadstoaninversion ofcontrolbetweentheapplicationandthesoftwareonwhichit'sbased.Whenyouuseatoolkitora conventionalsubroutinelibrarysoftwareforthatmatter,youwritethemainbodyoftheapplicationand callthecodeyouwanttoreuse.Whenyouuseaframework,youreusethemainbodyandwritethecodeit calls.... Thelinearrecursivestructure IList coupledwiththevisitorsasshownintheaboveisoneofthe simplest,non-trivial,andpracticalexamplesofframeworks.Ithasthecharacteristicof"inversionof control"describedinthequote.Itillustratestheso-calledHollywoodProgrammingPrinciple:Don'tcall me,Iwillcallyou.Imaginethe IList unionsittinginalibrary. Theabovelistframeworkdictatesthedesignofallalgorithmsoperatingontheliststructure: Allalgorithmsmustbesomeconcreteimplementationof IListAlgo Algorithmsthatrequiretheconstructionofemptyand/ornon-emptylists,mustdosoviasome abstractlistfactory, IListFactory Inordertoapplyanalgorithmtoalist,onemustaskalistto"execute"thatalgorithm,givingitthe requiredinputparameter. Whenwewriteanalgorithmonan IList inconformancewithitsvisitorinterface,wearewritingcode forthe IList tocallandnottheotherwayaround.Byadheringtothe IList framework'sprotocol,all algorithmsonthe IList canbedevelopedmuchmorequickly.Andbecausetheyallhavesimilarstructures, 10 http://cnx.org/content/m16796/latest/le:///C:%5CUsers%5Cdxnguyen.ADRICE%5CDocuments%5CMy%20Web%20Sites%5CRice%5Ccomp201%5Cpublic_html%5C08spring%5Clectures%5Clec20%5ClistFW%5Cdoc%5C 11 http://cnx.org/content/m16796/latest/le:///C:%5CUsers%5Cdxnguyen.ADRICE%5CDocuments%5CMy%20Web%20Sites%5CRice%5Ccomp201%5Cpublic_html%5C08spring%5Cds%5ClistFW.zip PAGE 71 65 theyaremucheasierto"maintain".The IList frameworkputspolymorphismtouseinaveryeective andelegant!waytoreduceowcontrolandcodecomplexity. Wedonotknowanythingabouthowtheabovelistframeworkisimplemented,yetwehavebeenableto writequiteafewalgorithmsandtestthemforcorrectness.Inordertoobtainconcretelistsandtestan algorithm,wecallonaconcrete IListFactory ,called CompositeListFactory ,tomanufactureemptyand non-emptylists.Wedonotknowhowthisfactorycreatesthoselistobjects,butwetrustthatitdoesthe rightthingandproducestheappropriatelistobjectsforustouse.Andsofar,itseemslikeit'sdoingits job,givingusallthelistsweneed. 3.4.55.BootstrappingAlong Let'stakealookbackatwhatwe'vedonewithalistsofar: 1.CreatedaninvariantlistinterfacewithtwovariantconcretesubclassesCompositepatternwhere anyalgorithmsonthelistwhereimplementedasmethodsoftheinterfaceandsubclassesInterpreter pattern 2.Extractedthevariantalgorithmsasvisitorsleavingbehindaninvariant"execute"method.Accessor methodsforrstandrestinstalled.Theentireliststructurenowbecomesinvariant. 3.Abstractedthecreationofalistintoaninvariantfactoryinterfacewithvariantconcretesubclass factories. 4.Separatedthelistframeworkintoaninvarianthierarchyofinterfacesandavariantimplementation whichwashiddeninsideofavariantfactoryclass. Istheresomethingsystematicgoingonhere? Noticethatateverystageinourdevelopmentofourcurrentlistframework,wehaveappliedthe same abstractionprinciplestothethencurrentsystemtoadvanceittothenextstage.Specically,wehave identiedandseparatedthevariantandinvariantpiecesofthesystemanddenedabstractrepresentations wheneverneeded. Thisreallytellsusaboutsomegeneralcharacteristicsofsoftwaredevelopment: Softwaredevelopmentisaniterativeprocess.Younevergettherightanswerthersttimeandyou havetoslowly"evolve"yourcodecloserandclosertowhatyouwant. Everytimeyouchangeyourcodeyoulearnsomethingmoreand/ornewaboutyoursystemand/or problem.Thisisbecauseeverynewformulationofyoursolutionrepresentsanewway,anewviewas itwere,ontheproblemandthisnewviewhighlightsaspectsyouhadn'tconsideredbefore. Therevisionprocessisdrivenalongbyarepetitiveapplicationoftheabstractdecompositiontechniques suchasseparatingthevariantandinvariant. Arewedonewithourlistrenements?Willweeverbe"done"?Whatdotheabovecharacteristicssay aboutthewayweshouldapproachsoftwaredevelopment? Also,nowthatwehavemanagedtoabstractstructure,behaviorandconstruction,isthereanythingleft toabstract?Oristhereonemorepiecetoourabstractionpuzzleatleast? 3.5InnerClasses 12 3.5.11.HelpersaretheVariants Consideragainthefamiliarproblemofcomputinga String representationofan IList thatdisplaysa comma-separatedlistofitselementsdelimitedbyapairofmatchingparentheses.Wehaveseenatleastone waytocomputesucha String representationusingavisitorcalled ToStringAlgo .Belowarethreedierent algorithms, ToString1 ToString2 and ToString3 ,thatcomputethesame String representation. 12 Thiscontentisavailableonlineat PAGE 72 66 CHAPTER3.IMMUTABLELISTSTRUCTURE PAGE 73 67 MainVisitor ToString1 Tail-recursivehelper ToString1Help packagelistFW.visitor; importlistFW.*; publicclassToString1implementsIListAlgo{ publicstaticfinalToString1Singleton=newToString1; privateToString1{ } publicObjectemptyCaseIMTListhost,Object...nu{ return""; } publicObjectnonEmptyCaseINEListhost,Object...nu{ returnhost.getRest.executeToString1Help.Singleton, ""+host.getFirst; } } /** *HelpsToString1computetheStringrepresentationoftherestofthelist. *Ittakesasinputtheaccumulatedstringrepresentationofthepreceding *list.Thisaccumulatedstringcontainstheleftmostparenthesisandall *theelementsoftheprecedinglist,eachseparatedbyacomma. */ classToString1HelpimplementsIListAlgo{ publicstaticfinalToString1HelpSingleton=newToString1Help; privateToString1Help{ } publicObjectemptyCaseIMTListhost,Object...acc{ returnacc[0]+""; } publicObjectnonEmptyCaseINEListhost,Object...acc{ returnhost.getRest.executethis,acc[0]+"," +host.getFirst; } } continuedonnextpage PAGE 74 68 CHAPTER3.IMMUTABLELISTSTRUCTURE Table3.17 MainVisitor ToString2 Tail-recursivehelper ToString2Help packagelistFW.visitor; importlistFW.*; publicclassToString2implementsIListAlgo{ publicstaticfinalToString2Singleton=newToString2; privateToString2{ } publicObjectemptyCaseIMTListhost,Object...nu{ return""; } publicObjectnonEmptyCaseINEListhost,Object...nu{ returnhost.getRest.executeToString2Help.Singleton, host.getFirst.toString; } } /** *HelpsToString2computetheStringrepresentationoftherestofthelist. */ classToString2HelpimplementsIListAlgo{ publicstaticfinalToString2HelpSingleton=newToString2Help; privateToString2Help{ } publicObjectemptyCaseIMTListhost,Object...acc{ return""+acc[0]+""; } publicObjectnonEmptyCaseINEListhost,Object...acc{ returnhost.getRest.executethis, acc[0]+","+host.getFirst; } } continuedonnextpage PAGE 75 69 Table3.18 MainVisitor ToString3 Nontail-recursivehelper ToString3Help packagelistFW.visitor; importlistFW.*; publicclassToString3implementsIListAlgo{ publicstaticfinalToString3Singleton=newToString3; privateToString3{ } publicObjectemptyCaseIMTListhost,Object...nu{ return""; } publicObjectnonEmptyCaseINEListhost,Object...nu{ return""+host.getFirst +host.getRest.executeToString3Help.Singleton; } } /** *HelpsToString3computetheStringrepresentationoftherestofthelist. */ classToString3HelpimplementsIListAlgo{ publicstaticfinalToString3HelpSingleton=newToString3Help; privateToString3Help{ } publicObjectemptyCaseIMTListhost,Object...nu{ return""; } publicObjectnonEmptyCaseINEListhost,Object...nu{ return","+host.getFirst +host.getRest.executethis; } } continuedonnextpage PAGE 76 70 CHAPTER3.IMMUTABLELISTSTRUCTURE Table3.19 Whatmakeseachoftheabovedierentfromoneanotherisitshelpervisitor.Eachhelperdenedin theabovewillonlyperformcorrectlyifitispassedtheappropriateparameter.Inasense,eachhelperisan implementationofthemainvisitor.Weshouldhideeachoftheminsideofitscorrespondingmainvisitorto ensureproperusageandachievefullencapsulationofthemainvisitor. 3.5.22.HidingHelpers Themostsecurewaytohidethehelpervisitoristomoveitinsideofthemainvisitorandmakeita private static class. HidingNamedHelperVisitorinsideof ToString1 Comments packagelistFW.visitor; importlistFW.*; publicclassToString1WithHiddenHelperimplementsIListAlgo{ publicstaticfinal ToString1WithHiddenHelperSingleton=newToString1WithHiddenHelper; privateToString1WithHiddenHelper{ } SingletonPattern privatestaticclassHiddenHelperimplementsIListAlgo{ publicstaticfinalHiddenHelperSingleton=newHiddenHelper; privateHiddenHelper{ } publicObjectemptyCaseIMTListhost,Object...acc{ returnacc[0]+""; } publicObjectnonEmptyCaseINEListhost,Object...acc{ returnhost.getRest.executethis,acc[0]+","+host.getFirst; } } Thehelpervisitorhasaname, HiddenHelper ,and isdenedprivatelyandglobally static insideof themainvisitor ToString1WithHiddenHelper continuedonnextpage PAGE 77 71 publicObjectemptyCaseIMTListhost,Object...nu{ return""; } publicObjectnonEmptyCaseINEListhost,Object...nu{ returnhost.getRest.executeHiddenHelper.Singleton,""+host.getFirst; } } Themainvisitorcallsonitshiddenhelpersingleton tohelpcompletethejob. Table3.20 HidingNamedHelperVisitorinsideof ToString2 Comments packagelistFW.visitor; importlistFW.*; publicclassToString2WithHiddenHelperimplementsIListAlgo{ publicstaticfinal ToString2WithHiddenHelperSingleton=newToString2WithHiddenHelper; privateToString2WithHiddenHelper{ } privatestaticclassHiddenHelperimplementsIListAlgo{ publicstaticfinalHiddenHelperSingleton=newHiddenHelper; privateHiddenHelper{ } publicObjectemptyCaseIMTListhost,Object...acc{ return""+acc[0]+""; } publicObjectnonEmptyCaseINEListhost,Object...acc{ returnhost.getRest.executethis,acc[0]+","+host.getFirst; } } continuedonnextpage PAGE 78 72 CHAPTER3.IMMUTABLELISTSTRUCTURE publicObjectemptyCaseIMTListhost,Object...nu{ return""; } publicObjectnonEmptyCaseINEListhost,Object...nu{ returnhost.getRest.executeHiddenHelper.Singleton,host.getFirst.toString; } } Table3.21 HidingNamedHelperVisitorinsideof ToString3 Comments packagelistFW.visitor; importlistFW.*; publicclassToString3WithHiddenHelperimplementsIListAlgo{ publicstaticfinal ToString3WithHiddenHelperSingleton=newToString3WithHiddenHelper; privateToString3WithHiddenHelper{ } privatestaticclassHiddenHelperimplementsIListAlgo{ publicstaticfinalHiddenHelperSingleton=newHiddenHelper; privateHiddenHelper{ } publicObjectemptyCaseIMTListhost,Object...nu{ return""; } publicObjectnonEmptyCaseINEListhost,Object...nu{ return","+host.getFirst+host.getRest.executethis; } } continuedonnextpage PAGE 79 73 publicObjectemptyCaseIMTListhost,Object...nu{ return""; } publicObjectnonEmptyCaseINEListhost,Object...bu{ return""+host.getFirst+host.getRest.executeHiddenHelper.Singleton; } } Table3.22 3.5.33.AnonymousHelpers AnonymousHelperVisitorinsideof ToString1 Comments packagelistFW.visitor; importlistFW.*; publicclassToString1WithAnonymousHelperimplementsIListAlgo{ publicstaticfinal ToString1WithAnonymousHelperSingleton=newToString1WithAnonymousHelper; privateToString1WithAnonymousHelper{ } privatestaticfinalIListAlgoAnonymousHelper=newIListAlgo{ publicObjectemptyCaseIMTListhost,Object...acc{ returnacc[0]+""; } publicObjectnonEmptyCaseINEListhost,Object...acc{ returnhost.getRest.executethis,acc[0]+","+host.getFirst; } };//PAYATTENTIONTOTHESEMI-COLONHERE! continuedonnextpage PAGE 80 74 CHAPTER3.IMMUTABLELISTSTRUCTURE publicObjectemptyCaseIMTListhost,Object...nu{ return""; } publicObjectnonEmptyCaseINEListhost,Object...nu{ returnhost.getRest.executeAnonymousHelper,""+host.getFirst; } } Table3.23 AnonymousHelperVisitorinsideof ToString2 Comments packagelistFW.visitor; importlistFW.*; publicclassToString2WithAnonymousHelperimplementsIListAlgo{ publicstaticfinal ToString2WithAnonymousHelperSingleton=newToString2WithAnonymousHelper; privateToString2WithAnonymousHelper{ } privatestaticfinalIListAlgoAnonymousHelper=newIListAlgo{ publicObjectemptyCaseIMTListhost,Object...acc{ return""+acc[0]+""; } publicObjectnonEmptyCaseINEListhost,Object...acc{ returnhost.getRest.executethis,acc[0]+","+host.getFirst; } };//PAYATTENTIONTOTHESEMI-COLONHERE! continuedonnextpage PAGE 81 75 publicObjectemptyCaseIMTListhost,Object...nu{ return""; } publicObjectnonEmptyCaseINEListhost,Object...nu{ returnhost.getRest.executeAnonymousHelper,host.getFirst.toString; } } Table3.24 AnonymousHelperVisitorinsideofToString3 Comments packagelistFW.visitor; importlistFW.*; publicclassToString3WithAnonymousHelperimplementsIListAlgo{ publicstaticfinal ToString3WithAnonymousHelperSingleton=newToString3WithAnonymousHelper; privateToString3WithAnonymousHelper{ } privatestaticfinalIListAlgoAnonymousHelper=newIListAlgo{ publicObjectemptyCaseIMTListhost,Object...nu{ return""; } publicObjectnonEmptyCaseINEListhost,Object...nu{ return","+host.getFirst+host.getRest.executethis; } };//PAYATTENTIONTOTHESEMI-COLONHERE! continuedonnextpage PAGE 82 76 CHAPTER3.IMMUTABLELISTSTRUCTURE publicObjectemptyCaseIMTListhost,Object...nu{ return""; } publicObjectnonEmptyCaseINEListhost,Object...nu{ return""+host.getFirst+host.getRest.executeAnonymousHelper; } } Table3.25 3.5.44.FactorywithAnonymousInnerClasses Comments packagelistFW.factory; importlistFW.*; publicclassInnerCompListFactimplementsIListFactory{ publicstaticfinalInnerCompListFactSingleton=newInnerCompListFact; privateInnerCompListFact{ } privatefinalstaticIListAlgoToStrHelp=newIListAlgo{ publicObjectemptyCaseIMTListhost,Object...acc{ returnacc[0]+""; } publicObjectnonEmptyCaseINEListhost,Object...acc{ returnhost.getRest.executethis,acc[0]+","+host.getFirst; } };//PAYATTENTIONTOTHESEMI-COLONHERE! continuedonnextpage PAGE 83 77 privatefinalstaticIMTListMTSingleton=newIMTList{ publicObjectexecuteIListAlgoalgo,Object...inp{ returnalgo.emptyCasethis,inp; } publicStringtoString{ return""; } };//PAYATTENTIONTOTHESEMI-COLONHERE! publicIMTListmakeEmptyList{ returnMTSingleton; } publicINEListmakeNEListfinalObjectfirst,finalIListrest{ returnnewINEList{ publicObjectgetFirst{ returnfirst; } publicIListgetRest{ returnrest; } publicObjectexecuteIListAlgoalgo,Object...inp{ returnalgo.nonEmptyCasethis,inp; } publicStringtoString{ returnStringrest.executeToStrHelp,""+first; } }; } } Notehowthecodeinsidetheanonymousinnerclass referencesrstandrestoftheparameterlist. first and rest aresaidtobeinthe closure oftheanonymousinnerclass. HereisanimportantJava syntaxrule: Foranlocalinnerclassdenedinsideofamethodtoaccessa local variableofthe method,thislocalvariablemustbedeclaredas final continuedonnextpage PAGE 84 78 CHAPTER3.IMMUTABLELISTSTRUCTURE Table3.26 Clickheretodownloadthecodeofalloftheabove 13 3.5.55.ClassesdenedinsideofanotherClass Besideseldsandmethods,aJavaclasscanalsocontainotherclasses.Andjustlikeaeldormethod denedinsideofaclass,aclassdenedinsideofanotherclasscanbestaticornon-static.Hereisthesyntax. classX{ //fieldsofX... //methodsofX... /** *namedclassYdefinedinsideofclassX: */ [public|protected|private][static][final][abstract]classY[extendsA][implementsB]{ //fieldsofY... //methodsofY... //classesofY... } } 3.5.5.1ScopeSpecier Whenanembeddedclassisdenedas static ,itiscalleda nestedclass Themembersi.e.elds, methods,classesofastaticnestedclasscanaccessonlystaticmembersoftheenclosing class. Whenanembeddedclassisnonstatic ,itiscalledan innerclass .Themembersofaninnerclasscan accessALLmembersoftheenclosingclass.Theenclosingclassanditsenclosingclass,ifany,andsoon containstheenvironmentthatcompletelydenestheinnerclassandconstituteswhatiscalledthe closure oftheinnerclass.Asallfunctionalprogrammersshouldknow,closureisapowerfulconcept.Oneofthe greateststrengthintheJavaprogramminglanguageisthecapabilitytoexpressclosuresviaclasseswith innerclasses.Weshallseemanyexamplesthatwillillustratethispowerfulconceptinothermodules. Innerclassesdonothavetobeanonymousasshownintheaboveexamples.Theycanbenamedaswell. 3.5.5.2AccessSpecier Justlikeanyotherclass,aclassdenedinsideofanotherclasscanbe public protected package private, or private 3.5.5.3ExtensibilitySpecier Justlikearegularclass,a nal nested/innerclasscannotextended. 3.5.5.4AbstractSpecier Justlikearegularclass,an abstract nested/innerclasscannotbeinstantiated. 13 http://cnx.org/content/m17220/latest/listFW.zip PAGE 85 79 3.5.5.5InheritanceSpecier Justlikearegularclass,annested/innercanextendanynon-nalclassandimplementanynumberof interfacesthatarewithinitsscope. 3.5.5.6Usage Nested classesareusedmostlytoavoidnameclashandtopromoteandenforceinformationhiding.Examples? Inner classesareusedtocreateatrun-timeobjectsthathavedirectaccesstotheinternalsofthe outerobjectandperformcomplextasksthatsimplemethodscannotdo.Mostofthetime,theyaredened anonymously.Forexamples," eventlisteners "forJavaGUIcomponentsareimplementedasinnerclasses. Thedynamicbehaviorandversatilityofthese"listeners"cannotbeachievedbytheadditionofasetofxed methodstoaGUIcomponent.WeshallstudyJavaeventhandlingsoon! Aninnerobjectcanbethoughtasanextensionoftheouterobject. 3.5.66.Closure Infunctionalprogramming,theclosureofafunction lamdba consistsofthefunctionitselfandanenvironmentinwhichthefunctioniswell-dened.InJava,afunctionisreplacedbyaclass.Aninnerclassisonly denedinthecontextofitsouterobjectandtheouterobjectoftheouterobject,etc....Aninnerclass togetherwithitsnestedsequenceofouterobjectsinwhichtheinnerclassiswell-denedistheequivalent ofthenotionofclosureinfunctionalprogramming.Suchanotionisextremelypowerful.Justlikeknowing howtoeectivelyuselambdaexpressionsandhigherorderfunctionsiskeytowritingpowerfulfunctional programsinScheme,eectiveusageofanonymousinnerclassesiskeytowritingpowerfulOOprogramsin Java. Someimportantpointstorememberaboutclosuresandinnerclasses: Anobject'sclosureisdenedatthetimeofitscreation. Anobject"remembers"itsclosureforitsentirelifetime. Aninnerobject'sclosureincludesanylocalvariablesthataredeclaredas final ,plusalleldsofthe enclosingobject,including private ones. Everytimeafactorymethodisrun,whereanewanonymousobjectiscreated,anewclosureforthat objectiscreated.Thisisbecausethelocalvariablescouldchangebetweencalls. Closuresenabledecoupledcommunicationbecauseaninnerclasscancommunicatewithitsouterclass throughitsclosure. Oneofthemostimportantwaysinwhichwewilluseanonymousinnerclassesittotakeadvantageoftheir closureproperties.AnonymousinnerclassesaretheonlyobjectsinJavathatcanbeinstantiatedinsuch amannerthatthevariablesintheirenvironmentsclosurescanbedynamicallydened.Thatis,sincean anonymousinnerclasscanreferencealocalvariablethatisdeclared final andsincelocalvariablesare createdeverytimeamethodiscalled,theneverytheanonymousinnerclassobjectcreatedhasadierent setofdynamicallycreatedvariablesthatitisreferencing.Thismeansthatwecanmakeuniqueobjectswith uniquebehaviorsatruntime. Factoriesareanaturalpartnerwithanonymousinnerclasses.Withafactorythatreturnsanonymous innerclasses,wecaninstantiateuniqueobjectswithuniquebehaviors.Ifthefactorymethodtakesinparameters,therelocalvariablescanbeusedtoaltertheresultantobject'sbehavior,aprocesscalled"currying 14 "namedafterthefamousmathematician/computerscientistHaskellCurry 15 .Theobjectsmadebythe factoryarethensentotovariousoddandsundrydierentpartsofourOOsystembutallthewhileretainingtheirclosures,whichweredeterminedatthetimeoftheirinstantiation.Thustheyretaintheability tocommunicatebacktothefactorythatmadethemeventhoughtheyarebeingusedinanotherpartofthe 14 http://en.wikipedia.org/wiki/Currying 15 http://www.haskell.org/bio.html PAGE 86 80 CHAPTER3.IMMUTABLELISTSTRUCTURE systemthatknowsnothingaboutthefactory.Weliketocallthese" spyobjects "becausetheyactlike spiesfromthefactory.Thisgivesuspowerfulcommunicationseventhoughthesystemisdecoupled. Thisisthelastpieceofourabstractionpuzzle!Wehave 1. AbstractStructure abstractclasses,interfaces 2. AbstractBehavior abstractmethods,strategies,visitors. 3. AbstractConstruction factories 4. AbstractEnvironments anonymousinnerclasses,closures. 3.5.6.1Examples Example1:Reversingalistusingfactoryandanonymousinnerclasshelper Write Reverse suchthatittakesoneparameter,the IListFactory ,butsuchthatitshelperonlytakesone parameterotherthanthehostlistwhichistheaccumulatedlist. publicclassReverseimplementsIListAlgo{ publicstaticfinalReverseSingleton=newReverse; privateReverse{} publicObjectemptyCaseIMTListhost0,Object...fac{ returnIListFactoryfac[0].makeEmptyList; } publicObjectnonEmptyCaseINEListhost0,Object...fac{ finalIListFactoryf=IListFactoryfac[0];//finalsothattheanon.innerclasscanaccessit. returnhost0.getRest.executenewIListAlgo{ publicObjectemptyCaseIMTListhost1,Object...acc{ returnacc[0]; } publicObjectnonEmptyCaseINEListhost1,Object...acc{ returnhost1.getRest.executethis, f.makeNEListhost1.getFirst,IListacc[0]; } },f.makeNEListhost0.getFirst,f.makeEmptyList; } } Example2:AntWorld Imagineaworldofantsthatliveinaone-dimensionalspace.Aqueenantcanmakeabunchofworkerants. Eachtimeshegivesbirthtoaworkerant,shegivesitaname.Aworkerantcanalwaystellwhatitsname is.Aworkerantfromaparticularcolonycanalwayscalculateitsdistancefromitsqueen.Aworkerantcan alsomoveitsqueentoadierentlocation.Whereverthequeenmovesto,ALLofherworkersalwaysknow theirrelativedistancefromher.Wewanttokeeptrackofalltheantsinourantworldandalltheantsin eachoftheexistingcolonies.Wewanttomodelthefactthateachqueenproducesitsownworkerants,each onewhichcanmoveitsqueenaroundwithouttellingtheotherantsinthesamecolony,yetALLoftheants inthesamecolonywouldknowwheretheirqueenis. TheabovecanbemodeledbyaQueenclasswithanabstractWorkerinnerclassasshownbelow.This exampleillustratesthedierencesbetweenstaticandnon-staticelds,methodsandembeddedclasses. PAGE 87 81 Queen.java /** *Modelsantslivingina1-dimensionalworld * *TheWorkerinnerobjectshavedirectaccesstothelocationofitsouter *Queenobject. *@authorA.L.Cox *@authorD.X.Nguyen *@authorS.B.Wong *@since02/07/2003 */ publicclassQueen{ /** *Thetotalnumberofantsqueensandworkersforallthequeensthat *currentlyexistinourantworld. *Whyisthisfieldstatic? */ privatestaticint_ants; /** *ThelocationofthisQueenobjectwithrespectto0. *Whyisthisfieldnon-static? */ privateint_origin; /** *ThetotalnumbersoflivingworkerantsproducedbythisQueenobject. *Whyisthisfieldnon-static? */ privateint_workers; /** *IspartofaQueeninstance,justliketheoriginfieldandthe *makeWorkermethodarepartsofaQueeninstance. *AnyconcreteimplementationofWorkermustimplementthegetName *methodtoreturnthenamegivenbyitsQueenatbirthtime. *Whycan'tthisclassbestatic? */ publicabstractclassWorker{ /** *ThelocationofthisWorkerobject. */ privateint_location; /** *Increments_antsand_workersbecauseeverytimeaWorkeris *instantiated,anewantisaddedtoourantworld,anewworkerant *isaddedtothecolonyofthisouterQueenobject. *@paramlocthestartinglocationofthisWorkerobject. */ publicWorkerintloc{ _location=loc; _ants++;//Theworkerisanant. _workers++; } /** *@returntherelativedistancebetweenthisWorkeranditsouterQueen *object. */ publicintcalcDist{ return_location-_origin; } /** *Thenamewillbegivenatbirth.Thecodecannotbewrittenat *thispointandthusmustbeabstract. *@returnnameoftheworker */ publicabstractStringgetName; /** *Ourworkerhasbeensteppedon!Nooneholdsareference *tothisobjectanymore.It'sbeinggarbagecollected. */ protectedvoidfinalize{ _ants--;//Theworkerisanant. _workers--; } /** *ChangesthelocationofthisWorkerobjecttoanewlocation. *@paramlocthenewlocationforthisWorlerobject. */ publicvoidmoveTointloc{ _location=loc; } /** *ChangestheoriginoftheouterQueenobjecttoanewlocation. *@paramorgtheneworiginfortheouterQueenobject. */ publicvoidmoveQueenintorg{ moveToorg; _origin=org; } } /** *InitializestheoriginofthisQueenobjecttoagivenlocation. *Increments_antssincethisnewQueenobjectisanant. *@paramorgthestartingoriginofthisQueenobject. */ publicQueenintorg{ _ants++;//Thequeenisanant. _origin=org; } /** *Returnthetotalnumberofallants,includingallofthe *queensandtheirrespectiveworkers. *Whyisthismethodstatic? *Canitbenon-static? */ publicstaticintcountAllAnts{ return_ants; } /** *@returnthetotalnumberofworkersthatbelongtothisQueenobject *Whyisn'tthismethodstatic? */ publicintcountMyWorkers{ return_workers; } /** *Factorymethod:relegatethetaskofmanufacturingconcrete *WorkerobjectstotheQueenobjectbecausetheQueenobject *intrinsically"knows"howtomakeitsinnerobjects. *@paramnameThenameoftheWorker. */ publicWorkermakeWorkerfinalStringname{ //AnonymouslycreateaWorkerobjectbyoverridinggetName. returnnewWorker_origin{ publicStringgetName{ returnname;//requirestheparameternametobefinal. } }; } } Figure3.5: Queen.java PAGE 88 82 CHAPTER3.IMMUTABLELISTSTRUCTURE 3.5.6.1.1Exercise: WriteaJUnittestprogramfortheQueenandWorkerclasses. 3.5.77.Changing"states"-progressingtonon-functionalprogramming IntheaboveQueenexample,thelocationsofa Queen objectandits Worker objectsaresubjecttochange. Everytimea Worker antmovesits Queen ,ithasthesideeectofchangingthe Queen 'sorigin.The Queen objectremainsthe"same".Thisseemslikeareasonablethingtohave.Inthefunctionalprogramming paradigm,tomovethe Queen ,the Worker antwouldhavetoinstantiateanew Queen objectwithanew locationandndawaytoassociateitselftothisnew Queen ,whichdoesnotseemtomodelthe"real" antworldverywell.Byallowingourobjectstochangetheirinternalstatesinappropriatesituations,our programmingmodelbecomesmore"realistic",moreecient,andinmanycases"simpler". Tofurtherillustratetherelevanceofstatechanges,considertheproblemofmovingtheminimumelement ofalistofintegerstothefrontofthelist.Sincethecurrent IList modelisimmutable,wecanonlysolve theproblembyreturningacopyoftheoriginallistwithitsminimumatthefront.Belowisanalgorithm tosolvetheproblemthatmakesuseofanaccumulatortoaccumulatethecurrentminimumandinternally updatesitasthelistisbeingtraversed.Note:thelistisassumedtoholdnoduplicatevalues. PAGE 89 83 Min2Front.java publicclassMin2FrontimplementsIListAlgo{ privateInteger_accMin;//accumulatedmin. privateIListFactory_fact; publicMin2FrontIListFactoryf{ _fact=f; } publicObjectemptyCaseIMTListmtHost,Object...nu{ returnmtHost; } publicObjectnonEmptyCaseINEListneHost,Object...nu{ //Weassign_accMinthefirstofLasacandidateforminimum: _accMin=IntegerneHost.getFirst; /** *LetusconsiderthesetSofallelementsinLthatprecedeL. *Sisclearlyempty.Atthispointwehaveestablishedthefollowing: *_accMinisanelementofLandissmallerthanallelementsofS. *WenowcallonananonymoushelpertooperateonLinordertofind *theminimumandremoveitfromL.Thishelperwillrecursively *traveseLtotheendinordertoobtaintheminimum,saveitin *_accMinandreconstructthehostlistLwithouttheminimumonitsway *backfromtherecursivelisttraversal. */ IListwithoutMin=IListneHost.executenewIListAlgo{ /** *Note:whenLexecutesthishelper,thiscaseiscalledsinceLis *notempty.Thusforthefirstcalltothismethod,hisL. *Weupdate_accMintoensurethatitisanelementofLandisthe *minimumofallelementsinLthatprecedestherestofthehost *parameterh.Thenwerecursivelycallthishelperonh.getRest *tosavetheminimumin_accMinandcreateacopyofh.getRest *thatdoesnotcontain_accMin. */ publicObjectnonEmptyCaseINEListh,Object...nu{ ifIntegerh.getFirst < accMin{ _accMin=first; } /** *Atthispoint,wehaveestablishedthefollowinginvariant: *_accMinisanelementofLandistheminimumofallelements *inLthatprecedesh.getRest. */ IListaccList=IListh.getRest.executethis,null; /** *Byinduction,_accMinisnowtheminimumofthewholeouter *hostlistL,andaccListisacopyofh.getRestthatdoes *notcontain_accMin. */ if!first.equals_accMin{ accList=_fact.makeNEListfirst,accList; } //accListisnowacopyofthehosthwithout_accMin. returnaccList; /** *Asnotedearlier,L.execute...callsnonEmptyCasesince *Lisnotempty.ThusthefirstcalltononEmptyCaseisthe *callwithLasthevalueforthehostparameterh.So,when *wereturnfromthisfirstcall,accListisacopyofLwithout *theminimumstoredin_accMin. */ } /** *ThismethodisonlycalledfrominsideofthenonEmptyCase *method.Theemptyhostparameterhmarkstheendoftheouter *hostlistL. *_accministhustheminimum.Theemptylististhusacopyof *theouterhostlistLfromthecurrentlistemptytotheend *thatdoesnotcontain_accMin. */ publicObjectemptyCaseIMTListh,Object...nu{ returnh; } },null;//NOTEthattheinputargumentisnullsincethehelperdoes //notneedit. /** *"Cons"theminimumtothefrontofthecopyofthehostthatdoesnot *containthisminimum. */ return_fact.makeNEList_accMin,withoutMin; } } Figure3.6: Min2Front.java PAGE 90 84 CHAPTER3.IMMUTABLELISTSTRUCTURE Intheabove,thecommentsarelongerthanthecode.Theabovecodeandcommentscanbegreatly simpliedifthelistismutable.Whatdoesitmeanforalisttobemutable? PAGE 91 Chapter4 MutableDataStructures 4.1StateDesignPattern 1 Whenmodelingreal-lifesystems,weoftenndthatcertainobjectsinoursystemseemtochange"state" duringthecourseofacomputation. Examplesofchangingstate: 1.Akittengrowsupintoacat 2.Acarrunsintoatelephonepoleandbecomesawreck. 3.Afriendissadoneday,happyanother,andgrumpyonyetanotherday. 4.Alistchangesfromemptytonon-emptywhenanelementisadded. 5.Afractalbecomesmorecomplexwhenitgrows 6.etc.etc. Thecatandthekittenarethesameanimal,buttheydon'tactidentically.Acarcanbedrivenbutawreck cannotyettheyarethesameentityfundamentally.Yourfriendisthesamehumanbeing,nomatterwhat theirmood.Whyshouldn'talistbethesamelistandafractalbethesamefractal? Whensomethingchangesstate,itisthesameobject,butyetitbehavesdierently .This phenomenonofhavinganobjectschangeitsbehaviorasifitweresuddenlybelongingtoawholedierent classofobjectsiscalled" dynamicreclassication ". Sofarwe'vebeenusingimmutabledata,andtocreateanon-emptylistfromanemptyone,requiredthat wemakeawholebrand-newlist.Withouruse assignment "="previously,we'vechangedthe value of avariable,butneverthe behavior theobjectitreferences. Considerthisnotion:Wewanttochangethetypeoftheobjectbutwewantto encapsulatethat change sothattheoutsideworlddoes not seethetypechange,onlythebehaviorchange. Let'sworkwithanexample: Remembertheoldarcadegame,"Frogger"?That'stheonewhereatrac-challengedamphibianattempts tohopacrossmultiplelanesofspeedingcarsandtrucks,hopefullywithoutbeingconvertedintotheroadkill-du-jour. Here'sanon-lineversion:http://www.gamesgnome.com/arcade/frogger/ 2 Well,let'slookatwhatafrogishere: Alivefrog Hasawell-denedposition Hasagreencolor Canmovefromplacetoplace 1 Thiscontentisavailableonlineat PAGE 92 86 CHAPTER4.MUTABLEDATASTRUCTURES Dieswhenhitbyavehicle. Ontheotherhand,adeadfrog Hasawell-denedposition Hasadecidedredcolor. Cannotmovefromplacetoplace Doesn'tdiewhenhitbyavehiclebecauseitisalreadydead. Usingourtrustyseparationofvariantandinvariant,wecanseethatthepositionofafrogisaninvariantbut alltheotherbehaviorsarevariants.Thuswewanttoseparateoutthesevariantsintotheirownsubclasses ofaninvariantabstractclass.Wethenusecompositiontomodelthefroghavinganabstractstate,which couldbeeitheraliveordead: Downloadthecodehere. 3 Figure4.1 Clickheretodownloadthefulljavadocdocumentationoftheabovecode. 4 Thevariantbehaviorsarerepresentedbytheabstract AFrogState ,withthe DeadState and LiveState implementingitsabstractbehaviors. Note:The IFrog interfaceistheresimplytoallowdierentformulationsofthefrogtoexist.Seethe QuestionSection4.1.3:Question:below. 3 http://cnx.org/content/m17225/latest/frog.zip 4 http://cnx.org/content/m17225/latest/frogDocs.zip PAGE 93 87 Forthosevariantbehaviors,allthemain Frog doesisto delegate passthecallontoandreturnthe resultoftothe _state thatithas.Ifthe _state isa LiveState ,thenthe Frog willactasifwerealive becausethe LiveState onlycontainslive-likebehaviors.Ontheotherhand,ifthestateisa DeadState ,then thedelegationtothe _state willproducedead-likebehavior.The LiveState 's getHit behaviorwillcause the Frog 's _state tochangefromreferencinga LiveState instancetoreferencinga DeadState instance. 4.1.1Noconditionalsareneeded!! 4.1.2TheFrogbehavesthewayitdoesbecauseofwhatitisatthatmoment, notbecauseofwhatitcangureoutaboutitselfthen. ThisisanexampleoftheStateDesignPattern.ClickhereformoreinformationontheStatedesignpattern. 5 Fromtheoutside,nothingabouttheinternalimplementationof Frog canbeseen.Allonecanseeis itspublicbehavior.Theimplementationsofthestatedesignpatternarecompletelyencapsulatedwithin thefrogpackage,inthisformulation..Forinstance,ifoneismovingalive Frog ,itwilldutifullymoveas directed,butifinthemiddlesomewhere,the Frog ishit,thenitwillimmediatelystopmoving,nomatter howmuchitisaskedtodoso.Ifoneischeckingitscolor,thelive Frog isahealthygreenbutrightafterits accident,itwillreportthatitisdeathlyred. NoticehowtheFrogchangesitsbehaviorandalwaysbehavescorrectlyforitssituation, withnoconditionalstatementswhatsoever 4.1.3Question: Averynicetechnique,whenitispossible,istoimplementtheStatepatternusinganonymousinnerclasses. Canyouwritean IFrog implementationthatencapsulatesthestatesusingnestedclassesandanonymous innerclasses? Itcanbedoneusingonlyonepubliclyvisibleclassandnopackagevisibleclassesatall. Theonlymethodsneededarethosespeciedby IFrog Howdoesusinganonymousinnerclassesreducethenumberofparameterspassedtothestate? Howdoesusingtheanonymousinnerclassesreducethenumberofnon-publicmethods? 4.1.4Onward! Lookingwaybacktothebeginningofthesemester,wenowhavetoask,"Canweusethistechnologyto createa mutable list?Howwillthisaectthevisitorsandtheirexecutefunction?"Hmmmm..... 4.2MutableLinearRecursiveStructure 6 4.2.11.StatePatternandDynamicReclassication Inprogramming,itisoftennecessarytohaveobjectswithwhichonecanstoredata,retrievedatawhen needed,andremovedatawhennolongerneeded.Suchobjectsareinstancesofwhatwecallcontainer structures. Amutablecontainerstructureisasystemthatmaychangeitsstatefromemptytonon-empty,and vice-versa.Forexample,anemptycontainerchangesitsstatetonon-emptyafterinsertionofanobject;and whenthelastelementofacontainerisremoved,itschangesitsstatetoempty.Figure1belowdiagramsthe statetransitionofacontainerstructure. 5 "StateDesignPattern" PAGE 94 88 CHAPTER4.MUTABLEDATASTRUCTURES Figure4.2: Statetransitiondiagramforcontainerstructures Foreachdistinctstate,thealgorithmstoimplementthemethodsdier.Forexample,thealgorithmfor theretrievemethodistrivialintheemptystate-itsimplyreturnsnull-whileitismorecomplicatedinthe non-emptystate.Thesystemthusbehavesasifitchangesclassesdynamically.Thisphenomenoniscalled dynamicreclassication.Thestatepatternisadesignsolutionforlanguagesthatdonotdirectlysupport dynamicreclassication.Thispatterncanbesummarizedasfollow. Deneanabstractclassforthestatesofthesystem.Thisabstractstateclassshouldprovideallthe abstractmethodsforalltheconcretesubclasses. Deneaconcretesubclassoftheaboveabstractclassforeachstateofthesystem.Eachconcretestate mustimplementitsownconcretemethods. Representthesystembyaclass,calledthecontext,containinganinstanceofaconcretestate.This instancerepresentsthecurrentstateofthesystem. Denemethodsforthesystemtoreturnthecurrentstateandtochangestate. Delegateallrequestsmadetothesystemtothecurrentstateinstance.Sincethisinstancecanchange dynamically,thesystemwillbehaveasifitcanchangeitsclassdynamically. BelowistheUMLclassdiagramforthestatedesignpattern 7 7 "StateDesignPattern" PAGE 95 89 Figure4.3: UMLclassdiagramforthestatedesignpattern 4.2.22.MutableLinearRecursiveStructureFramework Amutablelinearrecursivestructure LRStruct canbeintheemptystateorinanon-emptystate.Ifit isempty,itcontainsnoobject.Otherwise,itcontainsanobjectcalled rst ,anda LRStruct objectcalled rest .Whenweinsertadataobjectintoanempty LRStruct ,itchangesitstatetonon-empty.Whenwe removethelastelementfromannon-empty LRStruct ,itchangesitsstatetoempty.Wemodela LRStruct usingthestatepattern,andasinthecaseoftheimmutablelist,Section3.3wealsoapplythevisitor patterntoobtaina framework .BelowistheUMLclassdiagramofthe LRStruct framework.Becauseof thecurrentlimitationofourdiagrammingtool,weareusingthe Object[]input notationtorepresentthe variableargumentlist Object...input .Clickheretodownloadthecode 8 .Clickheretodownloadthe javadocdocumentation. 9 .Wewillstudytheimplementationcodeinthenextlecture. 8 http://cnx.org/content/m17265/latest/lrs.zip 9 http://cnx.org/content/m17265/latest/lrsdocs.zip PAGE 96 90 CHAPTER4.MUTABLEDATASTRUCTURES Figure4.4: StateandVisitorPatternsforMutableLinearRecursiveStructure Thepublicconstructor: LRStruct andthemethods: insertFront... removeFront... getFirst setFirst... getRest setRest... of LRStruct exposethestructureofan LRStruct totheclientandconstitutethe intrinsic structural behaviorofan LRStruct .Theyforma minimalandcomplete setofmethodsformanipulatingan LRStruct .Usingthem,aclientcancreateanempty LRStruct ,storedatainit,andremove/retrievedata fromitatwill. Themethod, PAGE 97 91 ObjectexecuteIAlgoalgo,Objectinp iscalledtheextensibility" hook ".Itallowstheclienttoaddanopen-endednumberofnewapplicationdependentbehaviorstothedatastructure LRStruct ,suchascomputingitslengthormergingone LRStruct withanother,withoutmodifyinganyoftheexistingcode.Theapplication-dependentbehaviorsof LRStruct are extrinsic behaviorsandareencapsulatedinaunionrepresentedbyavisitorinterfacecalled IAlgo Whenaclientprogramswith LRStruct ,he/sheonlyseesthepublicmethodsof LRStruct and IAlgo .To addanewoperationonan LRStruct ,theclientwritesappropriateconcreteclassesthatimplements IAlgo Theframeworkdictatestheoveralldesignofanalgorithmon LRStruct :sinceanalgorithmon LRStruct mustimplement IAlgo ,theremustbesomeconcretecodefor emptyCase... andsomeconcretecodefor nonEmptyCase... .Forexample, publicclassDoSomethingWithLRSimplementsIAlgo{ //fieldsandconstructorcode... publicObjectemptyCaseLRStructhost,Object...inp{ //someconcretecodehere... returnsomeObject;//maybenull. } publicObjectnonEmptyCaseLRStructhost,Object...inp{ //someconcretecodehere... returnsomeObject;//maybenull. } } Asillustratedintheabove,analgorithmon LRStruct is" declarative "innature.Itdoesnotinvolve anyconditionaltondoutwhatstatethe LRStruct isininordertoperformtheappropriatetask.Itsimply "declares"whatneedstobedoneforeachstateofthehost LRStruct ,andleavesittothepolymorphism machinerytomakethecorrectcall.Polymorphismisexploitedtominimizeowcontrolandreducecode complexity. Toperformanalgorithmonan LRStruct ,theclientmust"ask"the LRStruct to"execute"thealgorithm andpassestoitalltheinputsrequiredbythealgorithm. LRStructmyList=newLRStruct;//anemptylist //codetocallonthestructuralmethodsofmyList,e.g.myList.insertFront/*whatever*/ //NowcallonmyListtoperformDoSomethingWithLRS: Objectresult=myList.executenewDoSomethingWithLRS/*constructorargumentlist*/,-2.75,"abc"; WithoutknowinghowLRStructisimplemented,letuslookanexampleofanalgorithmonanLRStruct 4.2.33.Example ConsidertheproblemofinsertinganIntegerobject inorder intoa sorted listofIntegers.Letuscontrast theinsertinorderalgorithmsbetween IList ,theimmutablelist,and LRStruct ,themutablelist. PAGE 98 92 CHAPTER4.MUTABLEDATASTRUCTURES Insertinorderusingfactory Insertinorderusingmutation importlistFW.*; publicclassInsertInOrderimplementsIListAlgo{ privateIListFactory_fact; publicInsertInOrderIListFactorylf{ _fact=lf; } /** *Simplymakesanewnon-emptylistwiththegiven *parameternasfirst. *@paramhostanemptyIList. *@paramnn[0]isanIntegertobeinsertedinorderintohost. *@returnINEList. */ publicObjectemptyCaseIEmptyListhost,Object...n{ return_fact.makeNEListn[0],host; } /** *Basedonthecomparisonbetweenfirstandn, *createsanewlistorrecur! *@paramhostanon-emptyIList. *@paramnanIntegertobeinsertedinorderintohost. *@returnINEList */ publicObjectnonEmptyCaseINEListhost,Object...n{ returnIntegern[0] < Integerhost.getFirst? _fact.makeNEListn[0],host: _fact.makeNEListhost.getFirst, IListhost.getRest.executethis,n[0]; } } importlrs.*; publicclassInsertInOrderLRSimplementsIAlgo{ publicstaticfinalInsertInOrderLRSSingleton =newInsertInOrderLRS; privateInsertInOrderLRS{ } /** *Simplyinsertsthegivenparameternatthefront. *@paramhostanemptyLRStruct. *@paramnn[0]isanIntegertobeinsertedinorderintohost. *@returnLRStruct */ publicObjectemptyCaseLRStructhost,Object...n{ returnhost.insertFrontn[0]; } /** *Basedonthecomparisonbetweenfirstandn, *insertsatthefrontorrecurs! *@paramhostanon-emptyLRStruct. *@paramnn[0]isanIntegertobeinsertedinorderintohost. *@returnLRStruct */ publicObjectnonEmptyCaseLRStructhost,Object...n{ ifIntegern[0] < Integerhost.getFirst{ returnhost.insertFrontn[0]; } else{ returnhost.getRest.executethis,n[0]; } } } continuedonnextpage PAGE 99 93 Note thattheinsertinorderalgorithmfor LRStruct neednotcreateanynewlistandthusneedsno factory.Downloadtheabovecode:lrs.zip 10 Table4.1 4.3BinaryTreeStructure 11 Upuntilnow,wehavebeenorganizingdataina"linear"fashion:oneitemafteranother.Thecorresponding datastructuresaretheimmutableschemelist IList andthemutablelinearrecursivestructure LRStruct Now,supposewewanttomodelsomethinglikethefollowingorganizationchart. Figure4.5 Astructureofdatasuchastheaboveiscalleda tree .Werstdesignaspecialkindof mutable tree structurecalledbinarytrees. 4.3.11.BinaryTreeObjectModel Denition4.1:BinaryTree Amutablebinarytree, BiTree ,canbeinanemptystateoranon-emptystate: Whenitisempty,itcontainsnodata. Whenitisnotempty,itcontainsadataobjectcalledtherootelement,and2distinct BiTree objectscalledtheleftsubtreeandtherightsubtree. 10 http://cnx.org/content/m17265/latest/lrs.zip 11 Thiscontentisavailableonlineat PAGE 100 94 CHAPTER4.MUTABLEDATASTRUCTURES Weimplementtheaboveobjectstructurewithacombinationofstate/composite/visitorpatterns,ina manneranalogousto LRStruct 12 Belowisthepublicinterfaceofthebinarytreeframework.Clickhereforjavadocdocumentation. 13 Figure4.6 TheimplementationdetailsaregiveninthefollowingUMLclassdiagram.Clickhereforjavadocdocumentation. 14 12 http://cnx.org/content/m17289/latest/lrs-javadocs.zip 13 http://cnx.org/content/m17289/latest/brs-javadocs.zip 14 http://cnx.org/content/m17289/latest/brs-javadocs.zip PAGE 101 95 Figure4.7 PAGE 102 96 CHAPTER4.MUTABLEDATASTRUCTURES 4.3.22.ImplementationDetails note: Clickhereforsourcecode. 15 Thecodefor BiTree istrivial,asitsimplydelegatesmostcallstoitsstate,therootnode.Therealworkis doneinthestate.Thecodefor EmptyNode and DatNode forthemostpartareequallytrivial.Theinsertion andremovaloftherootdataofa BiTree requiresomeworkandneedsomeexplanation.Whendoesitmake sensetoremovetherootnodefromabinarytree?Thatis,whencanoneunambiguouslyremovetheroot nodefromabinarytree? Clearly,whenbothsubtreesofarootnodearenon-empty,thenremovingtherootnodeisproblematic. However,itmakessensetoallowrootremovalwhenatleastoneofthesubtreesisempty.Supposeoneof thesubtreesisempty,then BiTree.remRoot willchangethestateofthisBiTreetothestateoftheother subtree.Forexample,whentheleftsubtreeisempty,rootremovaloftheparenttreewillsettheparenttree toitsrightsubtree. a EmptyNode b DatNode Figure4.8: aEmptyNodebDatNode 4.3.33.TheBestTreePrintingAlgorithminTexas Considerthebinarytreedisplayedinthefollowing"horizontal"manner: 62 _______________|_________________ || 207 _____|__________________|______ |||| []18[][] _________|______ || 39[] _____|_____ || [][] Suchhorizontaldisplayofatreeisnotveryconvenientwhenthetreeiswide.Itismoreconvenientto displaythetreeina"vertical"manner. Thefollowingvisitoranditshelperprinttheabovetree"vertically"asshownbelow: 62 15 http://cnx.org/content/m17289/latest/brs.zip PAGE 103 97 |_20 ||_[] ||_18 ||_39 |||_[] |||_[] ||_[] |_7 |_[] |_[] Let'sstudythealgorithm. ab Figure4.9 4.4ArraysandArrayProcessing 16 Therearemanywaystostoredata.Sofar,wehavecoveredlinearrecursivestructures,lists,andbinary recursivestructures,trees.Let'sconsideranotherwayofstoringdata,asacontiguous,numberedindexed setofdatastorageelements: anArray= itemA itemB itemC itemD itemE itemF itemG itemH itemI itemJ 0 1 2 3 4 5 6 7 8 9 Table4.2 This" array "ofelementsallowsustoaccessanyindividualelementusinganumberedindexvalue. Denition4.2:array Atitsmostbasicform,arandomaccessdatastructurewhereanyelementcanbeaccessedby specifyingasingleindexvaluecorrespondingtothatelement. Example anArray[4] givesus itemE .Likewise,thestatement anArray[7]=42 shouldreplace itemH with 42 note: Noticehowever,thattheabovedenitionis not arecursivedenition.Thiswillcause problems. 16 Thiscontentisavailableonlineat PAGE 104 98 CHAPTER4.MUTABLEDATASTRUCTURES 4.4.1ArraysinJava Arrays... arecontiguousinmemorysetsofobjectreferencesorvalues,forprimitives, areobjects, aredynamicallycreatedvia new ,and maybeassignedtovariablesoftype Object orprimitives Anarrayobjectcontainszeroormore unnamed variablesofthe same type.Thesevariablesare commonlycalledthe elements ofthearray. Anon-negativeintegerisusedtonameeachelement.Forexample, arrayOfInts[i] referstothe i+1 stelementinthe arrayOfInts array.Incomputer-ese,anarrayissaidtobea"randomaccess" container,becauseyoucandirectlyandIsuppose,randomlyaccessanyelementinthearray. Anarrayhasalimitedamountofintelligence,forinstance,itdoesknowitsmaximumlengthatall times,e.g. arrayOfInts.length Arrayshavetheadvantagethatthey providerandomaccesstoanyelement arefast. requireminimumamountsofmemory MoreinformationonarrayscanbefoundintheJavaResourceswebsitepageonarrays 17 note: Arraysaresizeandspeedataprice. 4.4.1.1ArrayTypes Anarraytypeiswrittenasthenameofanelementtypefollowedbyoneormoreemptypairsofsquare brackets. Forexample, int[] isthetypecorrespondingtoaone-dimensionalarrayofintegers. Anarray'slengthisnotpartofitstype. Theelementtypeofanarraymaybeanytype,whetherprimitiveorreference,includinginterface typesandabstractclasstypes. 4.4.1.2ArrayVariables Arrayvariablesaredeclaredlikeothervariables:adeclarationconsistsofthearray'stypefollowedby thearray'sname.Forexample, double[][]matrixOfDoubles; declaresavariablewhosetypeisa two-dimensionalarrayofdouble-precisionoating-pointnumbers. Declaringavariableofarraytypedoesnotcreateanarrayobject.Itonlycreatesthevariable,which cancontainareferencetoanarray. Becauseanarray'slengthisnotpartofitstype,asinglevariableofarraytypemaycontainreferences toarraysofdierentlengths. Tocomplicatedeclarations,C/C++-likesyntaxisalsosupported,forexample, doublerowvector[],colvector[],matrix[][]; Thisdeclarationisequivalentto double[]rowvector,colvector,matrix[]; or 17 http://www.exciton.cs.rice.edu/JavaResources/Java/declarations.htm#Arrays PAGE 105 99 double[]rowvector,colvector; double[][]matrix; Pleaseusethelatter! 4.4.1.3ArrayCreation Arrayobjects,likeotherobjects,arecreatedwith new .Forexample, String[]arrayOfStrings= newString[10]; declaresavariablewhosetypeisanarrayofstrings,andinitializesittoholda referencetoanarrayobjectwithroomfortenreferencestostrings. Anotherwaytoinitializearrayvariablesis int[]arrayOf1To5={1,2,3,4,5}; String[]arrayOfStrings={"array", "of", "String"}; Widget[]arrayOfWidgets={newWidget,newWidget}; Onceanarrayobjectiscreated,itneverchangeslength! int[][]arrayOfArrayOfInt={{1,2 },{3,4}}; Thearray'slengthisavailableasanalinstancevariablelength.Forexample, int[]arrayOf1To5={1,2,3,4,5}; System.out.printlnarrayOf1To5.length; wouldprint. 4.4.1.4ArrayAccesses Indicesforarraysmustbe int valuesthataregreaterthanorequalto0andlessthanthelengthof thearray.Rememberthatcomputerscientistsalwayscountstartingatzero,notone! Allarrayaccessesarecheckedatruntime:Anattempttouseanindexthatislessthanzeroorgreater thanorequaltothelengthofthearraycausesan IndexOutOfBoundsException tobethrown. Arrayelementscanbeusedoneithersideofanequalssign: myArray[i]=aValue; someValue=myArray[j]; Accessingelementsofanarrayisfastandthetimetoaccessanyelementisindependentofwhereitis inthearray. Insertingelementsintoanarrayisveryslowbecausealltheotherelementsfollowingtheinsertion pointhavetobemovedtomakeroom,ifthatisevenpossible. 4.4.2ArrayProcessingUsingLoops MoreinformationonloopscanbefoundattheJavaResourceswebsitepageonloops 18 Themaintechniqueusedtoprocessarraysisthe forloop .A for loopisawayofprocessingeach elementofthearrayinasequentialmanner. Hereisatypical for loop: 18 http://www.exciton.cs.rice.edu/JavaResources/Java/loops.htm PAGE 106 100 CHAPTER4.MUTABLEDATASTRUCTURES //Sumthenumberofelementsinanarrayofints,myArray. intsum=0;//initializethesum forintidx=0;idx < myArray.length;idx++{//startidx@0;endidxatlength-1; //incrementidxeverytimetheloopisprocessed. sum+=myArray[idx];//addtheidx'thelementofmyArraytothesum } Thereareanumberofthingsgoingonintheabove for loop: Beforetheloopstarts ,theindex idx isbeingdeclaredandinitializedtozero. idx isvisibleonly withinthe for loopbodybetweenthecurlybraces. Atthebegnningofeachloopiteration ,theindex idx isbeingtestedina"terminationcondition", inthiscase, idx iscomparedtothelengthofthelist.Iftheterminationconditionevaluatesto false theloopwillimmediatelyterminate. Duringeachloopiteration ,thevalueofthe idx 'selementinthearrayisbeingaddedtotherunning sum. Aftereachloopiteration ,theindex idx isbeingincremented. Onecantraverseanarrayinanydirectiononewishes: //Sumthenumberofelementsinanarrayofints,myArray. intsum=0;//initializethesum forintidx=myArray.length-1;0 < =idx;idx--{//startidx@length-1;endidxat0; //decrementidxeverytimetheloopisprocessed. sum+=myArray[idx];//addtheidx'thelementofmyArraytothesum } Theaboveloopsumsthelistjustaswellastherstexample,butitdoesitfrombacktofront.Note however,thatwehadtobealittlecarefulonhowweinitializedtheindexandhowwesetupthetermination condition. Here'salittlemorecomplicatedloop: //Findtheindexofthesmallestelementinanarrayofints,myArray. intminIdx=0;//initializetheindex.Mustbedeclaredoutsidetheloop. if==myArray.lengththrownewNoSuchElementException"Emptyarray!";//nogoodifarrayisempty! else{ forminIdx=0,intj=1;j < myArray.length;j++{//startminIdx@0,startindex@1; //endindexatlength-1;incrementindexeverytimetheloopisprocessed. ifmyArray[minIdx] > myArray[j] minIdx=j;//foundnewminimum } } Someimportantthingstonoticeaboutthisalgorithm: Theemptycasemustbecheckedexplicitlynopolymorphismtohelpyououthere! Thedesiredresultindex cannot bedeclaredinsidetheforloopbecauseotherwiseitwon'tbevisible totheoutsideworld. PAGE 107 101 Becarefulaboutusingthe minIdx valueifthearraywasindeedemptyit'saninvalidvalue!Itcan't besettoavalidvaluebecauseotherwiseyoucan'ttellthedierencebetweenavaluethatwasnever setandonethatwas. The for loophastwoinitializationstatementsseparatedbyacomma. Theloopdoesworkcorrectlyifthearrayonlyhasoneelement,butonlybecausetheterminationcheck isdonebeforetheloopbody. Noticethattoprovethatthisalgorithmworksproperly,onemustmakeseparateargumentsabout theemptycase,theoneelementcaseandthen-elementcase.Contrastthistothemuchsimplerlist algorithmthatonlyneedsanemptyandnon-emptycases. Forconvenience,Java5.0nowoersacompactsyntaxusedfortraversing all theelementsofanarrayorof anythingthatsubclassestype Iterable 19 : MyType[]myArray;//arrayisinitializedwithdatasomewhere forMyTypex:myArray{ //codeinvolvingx,i.e.eachelementinthearray } Itisimportanttorememberthatthissyntaxisusedwhenonewantstoprocesseveryelementinanarrayor an Iterable object independentoforderofprocessing becauseJavadoesnotguaranteeatraversal order. Let'slookatanalgorithmwherewemightnotwanttoprocesstheentirearray: //Findthefirstindexofagivenvalueinanarray intidx=-1;//initializetheindextoaninvalidvalue. forintj=0;j < myArray.length;j++{//noinitialization;endindexatlength-1; //incrementindexeverytimetheloopisprocessed. ifdesiredValue==myArray[j]{//foundmatch! idx=j;//savetheindex. break;//breakoutoftheloop. } } Notes: Theonlywayyoucantellifthedesiredvaluewasactuallyfoundornotisifthe value of idx is-1or not.Thusthevalueof idx mustbecheckedbeforeitiseverused. Theresultant idx variablecannotbeusedastheindexinsidetheloopbecauseonewouldnotbeable totellifthedesiredvaluewasfoundornotunlessonealsocheckedthelengthofthearray.Thisis becauseifthedesiredvaluewasneverfound, idx attheendoftheloopwouldequalthelengthofthe array,whichisonlyaninvalidvalueifyoualreadyknowthelengthofthearray. The break statementstopsthelooprightawayandexecutionresumesatthepointrightafterendof theloop. Thereisacounterpartto break called continue thatcausesthelooptoimmediatelyprogresstothebeginning ofthenextiteration.Itisusedmuchmorerarelythan break ,usuallyinsituationswherethereareconvoluted anddeeplynested if else statements. Canyouseethatthepriceofthecompactsyntaxofforloopsisaclearunderstandabilityoftheprocess? 19 http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Iterable.html PAGE 108 102 CHAPTER4.MUTABLEDATASTRUCTURES 4.4.2.1Whileloops for loopsareactuallyaspecializedversionof while loops. while loopshavenospecialprovisionsfor initializationorloopincrementing,justtheterminationcondition. while loopsiteratethroughtheloopbodyuntiltheterminationconditionevaluatestoa false value. Thefollowing for loop: for[initializationstatement];[terminationexpr];[incrementstatement]{ [loopbody] } Isexactlyequivalenttothefollowing: { [initializationstatement]; while[terminationexpr]{ [loopbody] [incrementstatement]; } } Notetheoutermostcurlybracesthatcreatethescopingboundarythatencapsulatesanyvariabledeclared insidethe for loop. TheJavacompilerwillautomaticallyconverta for looptotheabove while loop. Hereistheabovealgorithmthatndsadesiredvalueinanarray,translatedfroma for looptoa while loop: //FindtheindexofthefirstoccuranceofdesiredValueinmyArray,usingawhileloop. { idx=-1;//initializethefinalresult intj=0;//initializetheindex whilej < myArray.length{//loopthroughthearray ifdesiredValue==myArray[j]{//checkiffoundthevalue idx=j;//savetheindex break;//exittheloop. } j++;//incrementtheindex } } Basically, for loopsgiveupsomeoftheexibilityofa while loopinfavorofamorecompactsyntax. PAGE 109 103 while loopsareveryusefulwhenthedataisnotsequentiallyaccessibleviasomesortofindex.Another usefulscenariofor while loopsiswhenthealgorithmiswaitingforsomethingtohappenorforavalueto comeintothesystemfromanoutsiderelativelysource. do while loopsarethesameas while loopsexceptthattheconditionalstatementisevaluatedatthe endoftheloopbody,notitsbeginningasina for or while loop. SeetheJavaResourceswebsitepageonloops 20 formoreinformationonprocessinglistsusingwhile loops. 4.4.2.2for-eachloops Anexceedinglycommon for -looptowriteisthefollowing; Stuff[]s_array=newStuff[n]; //fills_arraywithvalues forinti=0;i < s_array.length;i++{ //dosomethingwiths_array[i] } Essentially,theloopdoessomeinvariantprocessingoneveryelementofthearray. Tomakelifeeasier,Javaimplementsthe for-eachloop ,whichisjustanalternate for loopsyntax: Stuff[]s_array=newStuff[n]; //fills_arraywithvalues forStuffs:s_array{ //dosomethingwiths } Simpler,eh? Itturnsoutthatthefor-eachloopisnotsimplyrelegatedtoarray.Anyclassthatimplementsthe Iterable interfacewillwork.Thisisdiscussedinanothermodule,asitinvolvestheuseofgenerics. 4.4.3Arraysvs.Lists Innoparticularorder... Arrays: Fastaccesstoallelements. Fixednumberofelementsheld. Diculttoinsertelements. Canrunintoproblemswithuninitializedelements. Minimalsafetyforout-of-boundsindices. Minimalmemoryused Simplesyntax Mustuseproceduraltechniquesforprocessing. OftenincompatiblewithOOarchitectures. Diculttoprovethatprocessingalgorithmsarecorrect. Processingalgorithmscanbeveryfast. Processingalgorithmscanbeminimallymemoryintensive 20 http://www.exciton.cs.rice.edu/JavaResources/Java/loops.htm PAGE 110 104 CHAPTER4.MUTABLEDATASTRUCTURES Lists: Slowaccessexcepttorstelement,whichisfast. Unlimitednumberofelementsheld. Easytoinsertelements. Encounteringuninitializedelementsveryraretoimpossible. Impossibletomakeout-of-boundserrors. Notoptimizedformemoryusage. Morecumbersomesyntax. CanuseOOandpolymorphicrecursivetechniquesforprocessing. VerycompatiblewithOOarchitectures. Easytoprovethatprocessingalgorithmsarecorrect. Processingalgorithmscanbequitefastiftail-recursiveandusingatail-calloptimizingcompiler. Processingalgorithmscanbeverymemoryintensiveunlesstail-recursiveandusingatail-call optimizingcompiler. note: ArraysareoptimizedforsizeandrandomaccessspeedattheexpenseofOOdesignand recursion.Ifyoudonotneedspeedorlowmemory,donotuseanarray.Ifyoumustuseanarray, tightlyencapsulateitsothatitdoesnotaecttherestofyoursystem. PAGE 111 Chapter5 RestrictedAccessContainers 5.1RestrictedAccessContainers 1 5.1.1Introduction Stacksandqueuesareexamplesofcontainerswithspecialinsertionandremovalbehaviorsandaspecial accessbehavior. Insertionandremovalinastackmustbecarriedoutinsuchawaythatthelastdatainsertedistherst onetoberemoved.Onecanonlyretrieveandremoveadataelementfromastackbywayofspecialaccess pointcalledthe"top".Traditionally,theinsertionandremovalmethodsforastackarecalledpushand pop,respectively.pushinsertsadataelementatthetopofthestack.popremovesandreturnsthedata elementatthetopofthestack.Astackisusedtomodelsystemsthatexhibit LIFOLastInFirstOut insert/removalbehavior. Datainsertionandremovalinaqueuemustbecarriedoutinsuchawaythattherstonetobe insertedistherstonetoberemoved.Onecanonlyretrieveandremoveadataelementfromaqueue bywayofspecialaccesspointcalledthe"front".Traditionally,theinsertionandremovalmethodsfora queuearecalled enqueue and dequeue ,respectively.enqueueinsertsadataelementatthe"end"ofthe queue.dequeueremovesandreturnsthedataelementatthefrontofthequeue.Aqueueisusedtomodel systemsthatexhibit FIFOFirstInFirstOut insertion/removalbehavior.Forexample,onecanmodel amovieticketlinebyaqueue. Weabstractthebehaviorsofspecialcontainerssuchasstacksandqueuesintoaninterfacecalled IRAContainer speciedasfollows. 5.1.2RestrictedAccessContainers 5.1.2.1IRAContainer.java packagerac; importlistFW.*; /** *Definestheinterfaceforarestrictedaccesscontainer. */ publicinterfaceIRAContainer{ /** *Emptythecontainer. 1 Thiscontentisavailableonlineat PAGE 112 106 CHAPTER5.RESTRICTEDACCESSCONTAINERS *NOTE:Thisimpliesastatechange. *ThisbehaviorcanbeachievedbyrepeatedlyremovingelementsfromthisIRAContainer. *Itisspecifiedhereasaconveniencetotheclient. */ publicvoidclear; /** *ReturnTRUEifthecontainerisempty;otherwise,return *FALSE. */ publicbooleanisEmpty; /** *ReturnTRUEifthecontainerisfull;otherwise,return *FALSE. */ publicbooleanisFull; /** *Returnanimmutablelistofallelementsinthecontainer. *@paramfactformanufacturinganIList. */ publicIListelementsIListFactoryfact; /** *Removethenextitemfromthecontainerandreturnit. *NOTE:Thisimpliesastatechange. *@throwanExceptionifthisIRAContainerisempty. */ publicObjectget; /** *Addanitemtothecontainer. *NOTE:Thisimpliesastatechange. *@paraminputtheObjecttobeaddedtothisIRAContainer. *@throwanExceptionifthisIRAContainerisfull. */ publicvoidputObjectinput; /** *ReturnthenextelementinthisIRAContainerwithourremovingit. *@throwanExceptionifthisIRAContainerisempty. */ publicObjectpeek; } 1.Restricttheusersfromseeinginsideorworkingontheinsideofthecontainer. 2.Havesimpleputdataandgetmethods.Notethelackofspecicationofhowthedatagoesinor comesoutofthecontainer. 3.However,a"policy"mustexistthatgovernshowdataisadded"put"orremoved"get".Examples: Firstin/FirstoutFIFO"Queue" Lastin/FirstoutLIFO"Stack" Retrievebyranking"PriorityQueue" Randomretrieval 4.Thepolicyisvariantbehavior > abstractit. PAGE 113 107 ThebehavioroftheRACisindependentofexactlywhatthepolicydoes. TheRACdelegatestheactualadding"put"worktothepolicy. TheRACisonlydependentontheexistenceofthepolicy,notwhatitdoes. Thepolicyisa"strategy"foraddingdatatotheRAC.SeetheStrategydesignpattern 2 Strategypatternvs.Statepattern 3 soalike,yetsodierent! Themanufacturingofspecicrestrictedaccesscontainerswithspecicinsertionstrategywillbedoneby concreteimplementationsofthefollowingabstractfactoryinterface. 5.1.2.2IRACFactory.java packagerac; /** *AbstractFactorytomanufactureRACs. */ publicinterfaceIRACFactory{ /** *ReturnsanemptyIRAContainer. */ publicIRAContainermakeRAC; } 5.1.3Examples Thefollowingisanabstractimplementationof IRACFactory using LRStruct astheunderliningdata structure.Byvaryingtheinsertionstrategy,whichisanIAlgoontheinternal LRStruct ,weobtaindierent typesofRAC:stack,queue,random,etc. 2 http://cnx.org/content/m17037/latest/ 3 http://cnx.org/content/m17047/latest/ PAGE 114 108 CHAPTER5.RESTRICTEDACCESSCONTAINERS Figure5.1: UMLdiagramoftheabstractRACandRACfactorydenitionsplusafewconcreteRAC factories. Thesourcecodeforthefollowingexamplescanbedownloadedatthislink 4 5.1.3.1ALRSRACFactory.java packagerac; importlistFW.*; importlistFW.factory.*; importlrs.*; /** *Implementsafactoryforrestrictedaccesscontainers.These *restrictedaccesscontainersareimplementedusinganLRStructto *holdthedataobjects. */ publicabstractclassALRSRACFactoryimplementsIRACFactory{ /** *Implementsageneral-purposerestrictedaccesscontainerusing *anLRStruct.How? *Thenextitemtoremoveisalwaysatthefrontofthelistof *containedobjects.Thisisinvariant! *Insertionis,however,delegatedtoastrategyroutine;and 4 http://cnx.org/content/m17101/latest/rac.zip PAGE 115 109 *thisstrategyisprovidedtothecontainer.Thisstrategy *variestoimplementthedesiredkindofcontainer,e.g.,queue *vs.stack. *Thisnestedstaticclassisprotectedsothatclassesderivedfromits *factorycanreuseittocreateotherkindsofrestrictedaccess *container. */ protectedstaticclassLRSRAContainerimplementsIRAContainer{ privateIAlgo_insertStrategy; privateLRStruct_lrs; publicLRSRAContainerIAlgostrategy{ _insertStrategy=strategy; _lrs=newLRStruct; } /** *Emptythecontainer. */ publicvoidclear{ _lrs=newLRStruct; } /** *ReturnTRUEifthecontainerisempty;otherwise,return *FALSE. */ publicbooleanisEmpty{ returnBoolean_lrs.executeCheckEmpty.Singleton; } /** *ReturnTRUEifthecontainerisfull;otherwise,return *FALSE. *Thisimplementationcanholdanarbitrarynumberof *objects.Thus,alwaysreturnfalse. */ publicbooleanisFull{ returnfalse; } /** *Returnanimmutablelistofallelementsinthecontainer. */ publicIListelementsfinalIListFactoryfact{ returnIList_lrs.executenewIAlgo{ publicObjectemptyCaseLRStructhost,Object...nu{ returnfact.makeEmptyList; } PAGE 116 110 CHAPTER5.RESTRICTEDACCESSCONTAINERS publicObjectnonEmptyCaseLRStructhost,Object...nu{ returnfact.makeNEListhost.getFirst, IListhost.getRest.executethis; } }; } /** *Removethenextitemfromthecontainerandreturnit. */ publicObjectget{ return_lrs.removeFront; } /** *Addanitemtothecontainer. */ publicvoidputObjectinput{ _lrs.execute_insertStrategy,input; } publicObjectpeek{ return_lrs.getFirst; } } } /** *PackageprivateclassusedbyALRSRACFactorytocheckforemptinessofitsinternalLRStruct. */ classCheckEmptyimplementsIAlgo{ publicstaticfinalCheckEmptySingleton=newCheckEmpty; privateCheckEmpty{ } publicObjectemptyCaseLRStructhost,Object...input{ returnBoolean.TRUE; } publicObjectnonEmptyCaseLRStructhost,Object...input{ returnBoolean.FALSE; } } 5.1.3.2LRSStackFactory.java packagerac; importlrs.*; PAGE 117 111 publicclassLRSStackFactoryextendsALRSRACFactory{ /** *Createa``last-in,first-out''LIFOcontainer. */ publicIRAContainermakeRAC{ returnnewLRSRAContainernewIAlgo{ publicObjectemptyCaseLRStructhost,Object...input{ returnhost.insertFrontinput[0]; } publicObjectnonEmptyCaseLRStructhost,Object...input{ returnhost.insertFrontinput[0]; } }; } } 5.1.3.3LRSQueueFactory.java packagerac; importlrs.*; publicclassLRSQueueFactoryextendsALRSRACFactory{ /** *Createa``first-in,first-out''FIFOcontainer. */ publicIRAContainermakeRAC{ returnnewLRSRAContainernewIAlgo{ publicObjectemptyCaseLRStructhost,Object...input{ returnhost.insertFrontinput[0]; } publicObjectnonEmptyCaseLRStructhost,Object...input{ returnhost.getRest.executethis,input; } }; } } 5.1.3.4RandomRACFactory.java packagerac; importlrs.*; /* PAGE 118 112 CHAPTER5.RESTRICTEDACCESSCONTAINERS *Implementsafactoryforrestrictedaccesscontainers,includinga *containerthatreturnsarandomitem. */ publicclassRandomRACFactoryextendsALRSRACFactory{ /** *Createacontainerthatreturnsarandomitem. */ publicIRAContainermakeRAC{ returnnewLRSRAContainernewIAlgo{ publicObjectemptyCaseLRStructhost,Object...input{ returnhost.insertFrontinput[0]; } publicObjectnonEmptyCaseLRStructhost,Objectinput{ /* *Math.Randomreturnsavaluebetween0.0and1.0. */ if.5 > Math.random returnhost.insertFrontinput[0]; else returnhost.getRest.executethis,input; } }; } } Butcanwepushtheabstractionfurther?Isthedierencebetweenastackandaqueuereallyanything morethanhowthedataisordered? Now,let'sgoonanlookattheorderingobjectandpriorityqueues... 5 5.2OrderingObjectandPriorityQueue 6 Placeholder.Contenttobeaddedlater. 5 http://cnx.org/content/m17064/latest/ 6 Thiscontentisavailableonlineat PAGE 119 Chapter6 GUIProgramming 6.1GraphicalUserInterfacesinJava 1 6.1.1GraphicalUserInterfacesinJava InJava GraphicalUserInterface GUI programming,wedonotbuildGUIcomponentsfromscratch. InsteadweuseGUIcomponentsprovidedtousbytheJDK.JavahastwotypesofGUIapplications:standaloneGUIapplicationsand applets .Werststudyhowtobuildstand-aloneGUIapplicationsGUIapp forshort. EveryGUIappuseswhatiscalleda JFrame thatcomeswiththeJDK.A JFrame isawindowwith borders,atitlebar,andbuttonsforclosingandmaximizingorminimizingitself.Italsoknowshowtoresize itself.EveryGUIappsubclasses JFrame insomewaytoaddmorefunctionalitytothewindowframe.One commontaskistotellthesystemtoterminateall"threads"oftheGUIappwhentheuserclicksontheexit closebuttonofthemainGUIwindow.Weencapsulatethistaskinanabstractframeclasscalled AFrame describedbelow. 6.1.20.AbstractFrameAFrame.java note: Thesourcecodefor AFrame isavailableintheglossary. 6.1.2.1Event WhentheuserinteractswithaGUIcomponentsuchasclickingonitorholdingthemousedownonitand dragthemousearound,theJavaVirtualMachineJVMresappropriate"events"anddeliversthemto theGUIcomponent.ItisuptotheGUIcomponenttorespondtoanevent.Theabstractnotionofeventsis encapsulatedinanabstractclasscalled AWTEvent providedbyJava.Specicconcreteeventsarerepresented byappropriateconcretesubclassesof AWTEvent Forexample,whentheuserclicksontheclosebuttonofa JFrame ,theJVMresawindowevent representedbytheclass WindowEvent anddeliversittothe JFrame .Bydefault,the JFrame simplyhides itselffromthescreenwhileeverythingelsethatwascreatedandrunningbeforethe JFrame disappearsfrom thescreenisstillaliveandrunning!Thereisnowaytheusercanredisplaytheframeagain.Inthecase whenthe JFrame isthemainwindowofaGUIapp,weshouldterminateeverythingwhenthismainframeis closed.Thebestwaytoensurethisactionisto"register"aspecialwindowevent"listener"withthe JFrame thatwillcalltheSystemclasstoterminateallthreadsrelatedtothecurrentprogramandexittheprogram. Thecodelookssomethinglikethis: 1 Thiscontentisavailableonlineat PAGE 120 114 CHAPTER6.GUIPROGRAMMING addWindowListenernewWindowAdapter{ publicvoidwindowClosingWindowEvente{ System.exit; } }; EverytimewewritetheconstructorforamainframeofaGUIapp,we invariably ndourselveswriting theabovelinesofcodetoexittheprogramplussomeadditionalapplicationspeciccodetoinitializethe frame.So,insteadof"copy-and-paste"theabovecode"opportunistic"re-use,wecapturethis invariant taskintheconstructorofanabstractclasscalled AFrame andreusethecodebysubclassingfromit. Theapplicationspeciccodetoinitializethemainframeisrelegatedtothespecicconcretesubclassof AFrame andisrepresentedbyanabstractmethodcalled initialize .Theconstructorfor AFrame calls initialize ,which,atrun-time,istheconcreteinitializationcodeoftheconcretesubclassof AFrame that isbeinginstantiated,asshownbelow. publicAFrameStringtitle{ //Alwayscallthesuperclass'sconstructor: supertitle; addWindowListenernewjava.awt.event.WindowAdapter{ publicvoidwindowClosingjava.awt.event.WindowEvente{ System.exit; } }; initialize; } note: Seethefull codelisting formoreinformation 6.1.2.2TemplateMethodPattern:ExpressingInvariantBehaviorintermsofVariantBehaviors note: Thecodefortheclasses AFrame FrameA FrameAB ,and FrameAC areavailablein theglossary. Thecodefor AFrame isanexampleofwhatiscalledtheTemplateMethodPattern 2 .Thisdesignpattern isusedtoexpressesan invariant andconcretebehaviorthatconsistsofcallstooneormore abstract methods.Anabstractmethodrepresentsa variant behavior.Inotherwords,thetemplatedesignpattern isameanstoexpressaninvariantbehaviorintermsofvariantbehaviors.Weshallseethispatternused againinexpressingsortingalgorithms. 6.1.2.2.1Caveat Asstatedearlier,thecallto initialize intheconstructorof AFrame willonlyinvoketheconcrete initialize methodoftheconcretedescendantclassof AFrame thatisbeinginstantiated.Because initialize ispolymorphic,caremusttakentoensureproperinitializationofdescendantclassesthatare 2 "TemplateDesignPattern" PAGE 121 115 morethanoneleveldeepintheinheritancehierarchyof AFrame .Considerthefollowinginheritancetreeas illustratedbythefollowingUMLclassdiagram.Clickheretoseethecode. Figure6.1 Inoverridingthe initialize methodof FrameA ,adirectsubclassof AFrame ,weshouldnot invokethe initialize methodofthesuperclass AFrame viathecall super.initialize because super.initialize isabstract.However,the initialize methodofanysubclassof FrameA andbelow shouldmakeacalltotheinitializemethodofitsdirectsuperclassinordertoensureproperinitialization. PAGE 122 116 CHAPTER6.GUIPROGRAMMING Forexample,intheabovediagram, newFrameAB"ab" callstheconstructor FrameAB ,whichcallsthe constructor FrameA ,whichcallstheconstructor AFrame ,whichcalls theconstructor JFrame andthencalls initialize ,whichisthe initialize methodof FrameAB whichcalls super.initialize ,whichshouldproperlyinitialize FrameA ,andthencalls theadditionalinitializationcodefor FrameAB Exercise6.1 Whatisthechainofcallswhenweinstantiatea FrameAC 6.1.31.SimpleJFrameFrame0.java note: Frame0App.javaisavailableinthesourcecodearchivele 3 Frame0App.java representsoneofthesimplestGUIapplicationinJava:itsimplypopsopenan Frame0 object. Frame0 issubclassof AFrame thatdoesnothinginitsconcrete initialize method. 6.1.42.JFramewithJButtonsbutnoeventhandlersFrame1.java note: Frame1.javaisavailableinthesourcecodearchivele 4 TodisplayotherGUIcomponentsona JFrame ,werstneedtogetthecontentpaneofthe JFrame andthen addthedesiredGUIcomponentstothiscontentpane. IfwewanttoarrangetheaddedGUIcomponentsincertainways,weneedtoaddanappropriate" layout manager "tothe JFrame .ThetaskoflayingouttheGUIcomponentinsideofacontainerGUIcomponent isspeciedbyaninterfacecalled LayoutManager .InFrame1,weaddthe FlowLayout thatarrangesall GUIcomponentsinalinearfashion.Ifwedonotaddanylayoutmanagertothe JFrame ,ithasnolayout manageranddoesaverybadjobofarrangingGUIcomponentsinsideofit.Asanexercise,commentout thecodetoaddthe FlowLayout toFrame1andseewhathappens! 6.1.4.1StrategyPattern JFrame isnotresponsibleforarrangingtheGUIcomponentsthatitcontains.Insteaditdelegatessuch atasktoitslayoutmanager, LayoutManager .Therearemanyconcretelayoutmanagers: FlowLayout BorderLayout GridLayout ,etc.thatarrangetheinternalcomponentsdierently.Therearesaidtobe dierentstrategiesforlayout.Theinteractionbetween JFrame anditslayoutmanagerissaidtofollowthe StrategyPattern 5 Thestrategypatternispowerfulandimportantdesignpattern.Itisbasedonthatprincipleofdelegation thatwehavebeenapplyingtomodelmanyoftheproblemssofar.Itisameantodelineatetheinvariant behaviorofthecontexte.g. JFrame andthevariantbehaviorsofaunionofalgorithmstoperformcertain commonabstracttaske.g. LayoutManager .Weshallseemoreapplicationsofthestrategydesignpattern infuturelessons. Atthispointtheonlythebuttonsinthe Frame1 exampledonotperformanytaskbesides"blinking" whentheyareclickedupon.Theexampleinthenextlecturewillshowhowtoassociateanactiontothe clickevent. Clickheretodownloadcodesamples. 6 3 http://cnx.org/content/m17185/latest/GUI1.zip 4 http://cnx.org/content/m17185/latest/GUI1.zip 5 "StrategyDesignPattern" PAGE 123 117 6.2MoreJavaGUIProgramming 7 6.2.11.JFramewithJButtonsandeventhandlersFrame2.java note: Clickheretoview Frame2.java ,ordownloadtheentirearchive 8 6.2.1.1CommandDesignPattern Whenauserclicksonabutton,an ActionEvent objectisdeliveredtothebutton.Inorderforthebuttonto performanapplicationspecictask,wemustregisteran ActionEventListener tothebuttonandprogram thiseventlistenertoperformthetaskwewant.The ActionListener classisanexampleofwhatiscalleda command "fromtheCommandDesignPattern 9 .Thecodetoaddan ActionListener toabuttonlooks like: myButton.addActionListenernewActionListener{ publicvoidactionPerformedActionEvente{ //codetoperformataskgoeshere... } }; Theexample Frame2 showshowtodynamicallychangethelayoutmanagerfora JFrame bycallingits setLayout... methodresultinginadynamicre-arrangementoftheGUIcomponentsinthe JFrame 6.2.22.JFramewithJButtonsandAdaptersFrame3.java note: Clickheretoview Frame3.java ,ordownloadtheentirearchive 10 Frame3 illustrateshowtodecoupletheviewfromtherestoftheworldbyhavingtheviewcommunicate toaninterfacecalled"adapter".Acontrollerobject, Frame3Controller connectstheview Frame3 tothe worldbyinstallingaconcreteadapterintotheview.Theadapterisinstantiatedasanonymousinnerobject andhasaccesstoallofitsouterobject.Theviewdoesnotandshouldnotknowanythingabouttheworld towhichitisconnected.Thisaddsexibilitytothedesign. 7 Thiscontentisavailableonlineat PAGE 124 118 CHAPTER6.GUIPROGRAMMING Figure6.2 6.2.2.1Null-ObjectPattern Inmuchofthecurrentprogrammingpractice,thespecialvalue null isoftenusedasaagtorepresenta gamutofdierentandoftendisconnectedconceptssuchasemptinessandfalseness.Thiscanresultinalot ofconfusionandcomplexcontrolstructuresinthecode.Inourview, null shouldonlybeusedtodenotethe non-existenceofanobject. null isnotanobjectandhasno"intelligence"i.e.behaviorforotherobjects tointeractwith.Therefore,wheneverweworkwitha union ofobjectsanddiscoverthatoneormoreof theseobjectsmaybereferencinga null value,wealmostalwayshavetowritecodetodistinguish null as aspecialcase.Toavoidthisproblem,weshouldthinkofaddingaspecialobject,calledthe nullobject tothe union withappropriatebehaviorthatwillallowustotreatallobjectreferencesinaconsistentand uniformway,devoidofspecialcaseconsideration.Thisdesignpatterniscalledthenullobjectpattern.We haveusedthenullobjectpatterninoneoccasion:the EmptyNode torepresenttheemptystateofamutable list LRStruct . PAGE 125 119 InFrame3theviewadapter, _v2wAdapter ,isinitializedtoananonymous IView2World object.It istheretoguaranteethat_ v2wAdapter isalwaysreferencingaconcrete IView2World object,and,since setV2WAdapter... onlyallowsanon-nullassignment,wecanalwayscallon_ v2WAdapter toperform anymethodwithoutcheckingfor null . PAGE 126 120 CHAPTER6.GUIPROGRAMMING PAGE 127 Chapter7 Labs 7.1DrJava 1 DrJavaisalightweightpedagogicalenvironmentforJavadevelopmentcreatedbyRiceUniversity.DrJava providesawaytoeditandsavejavacodewithkeywordshighlighting,curlybracematching,andan interactiveenvironmenttomanipulateobjectsandtestcodewithouthavingtowritethemainmethod.It canbefreelydownloadedfromtheWEB.PleaseseetheDrJavahomepage 2 7.1.1Editing DenitionsPane: WhenyourunDrJavayouwillseeawindowappear.ThiswindowGUIconsists offoursubwindows.ThetophalfoftheGUIconstitutestheDenitionspane.Youtypeinalltheclass denitionshere.Afteryoutypeinsomecode,youneedtoclickonthesavebuttonbeforeyoucancompile yourcode.AlltheclassesintheDenitionspanewillbesavedinasinglele.Thereshouldonlybeone publicclassintheDenitionswindow,andthesavedleshouldhavethesamenameasthatofthepublic classwiththeextension .java 7.1.2Compiling CompilerOutputPane: YoucompileyourJavacodebyclickingonthe CompileAll buttoninthe menubaratthetop.Everytimeyoucompileyourcode,DrJavawilldisplayallcompileerrormessages here.Clickingonanerrormessagewillhighlightthelinewheretheerrorissuspectedtotakeplaceinthe Denitionspane.Ifthereisnocompileerror,DrJavawilldeclaresuccessinthispane. 7.1.3Running Interactionspane: ThereareseveralwaystorunyourJavacode.Fornow,wewillrestrictourselves totheInteractionpaneatthebottomofthemainGUIwindow.Thisiswhereyoucantypeinanyvalid Javastatement.Usually,youwouldtypeincodetoinstantiateobjectsofclassesdenedintheDenitions window,andcalltheirmethodstocheckwhetherornottheyperformcorrectly.TypingavalidJava expressionterminatedwithasemi-colonandthenpressingthe Return Enter key,willcauseDrJavato evaluatetheexpressionbutNOTprintingtheresult.IfyouwantDrJavatoprintthevalueoftheresult intheInteractionswindow,youshouldpress Return withoutterminatingtheexpressionwithasemi-colon. Thereisamenuitemtoreseti.e.cleartheInteractionswindow.AnotherwaytocleartheInteractions windowistoforceare-compilebyeditingtheDenitionspane.Ifyourcodehasprintingstatements,the outputwillbedisplayedintheConsoleOutputpane. 1 Thiscontentisavailableonlineat PAGE 128 122 CHAPTER7.LABS 7.1.4Testing Therearemanywaystotestyourcode.ThemostformalwayistouseJUnittestingfacilities,whichis coveredinaseparatemodule:UnitTestingwithJUnitinDrJavaSection7.2.Forsimpletests,youcan testyourcodebydirectlyinteractingwithitintheInteractionspane. 7.1.5Debugging TodebugaprograminDrJava,rstputDrJavainto DebuggingMode bysettingthecheckboxunder the Debugger onthemainmenu.Thiswillenablealltheotherdebuggingfeatures.Whendebuggingmode isactive,thedebuggingpanewillappearnearthebottomoftheDrJavawindow.Thispanecontainsthe Watch windowandtabsthatshowthecurrent Stack and Threads status.Thedebuggingpanealsohas buttonsfor Resume debugging, StepInto StepOver and StepOut .Thesefeaturesaredescribedin detailbelow. Thebasictechniquefordebuggingistoset breakpoints onlinesofcodethatareofinterest/problematic andthentoeitherstepslowlythroughthecodeexecutionfromthatpointand/ortoexaminethevaluesof variousvariables. Breakpoints :Underdebuggingmode,DrJavawillstoptheexecutionofaprogramwheneverabreakpointisencountered.Executionstops before thebreakpointslineofcodeisrun.Tosetorclearabreakpoint, placethecursoronthedesiredlineofcodeandeitherusethe Debugger/ToggleBreakpointonCurrent Line orbysimplypressing Ctrl-B orbyright-clickingthedesiredlineandselecting ToggleBreakpoint Notethatitonlymakessensetoputabreakpointonalineofcodethatactuallyexecutes,which excludes Blanklines Comments Methodsignaturelines Lineswithasinglecurlybraceonthem. Field/attributedeclarationsthathavenoinitializationcode. To clearabreakpoint ,followthesameprocedureusedtosetthebreakpoint. Whenevertheprogramexecutionisstoppedonalineofcode,the Interactionspane canbeusedto examinethevalueofanyvariablethatisinscopeoreventoexecutemethodsonthosevariablesiftheyare objects.Youcanevensetthevaluesofanyavailablevariablesbyassigninganewvaluetothem.Thisis usefuliftheyhavethewrongvalueforsomereasonandyouwanttocheckiftherestofyourcodewillrun properlyifthecorrectvalueispresent. ClearAllBreakpoints :Clickingon Debugger/ClearAllBreakpoints willclearallbreakpoints thathavebeensetinyourprogram. Clickingon Debugger/Breakpoints orpressing Ctrl+Shift+B willbringupatabbedpaneatthe bottomoftheDrJavawindowthatenablesyoutoconvenientlyexamine,navigateto,delete,ordisble withoutdeletingallofthebreakpointsinyourprogram. StepInto :Whenexecutionhasstoppedonalineofcode,clickingonthe StepInto buttoninthe debuggingpaneorselectingthemenuitem Debugger/StepInto orpressing F12 willcausethecurrent lineofcodehighlightedinbluetobeexecuted.Ifthecurrentlineofcodeinvolvestheinvocationofa method,thenthecurrentlineofcodewillbeadvanced into therstmethodtobecalled,asperJava'sorder ofexecutionrules.Ifthecurrentlineofcodeisthelastlineinamethod,thecurrentlineofcodewillbecome thenextexecutablelineofcodeinthemethodthat called thecurrentmethod.Notethatifthecaller'sline ofcodeinvolvedmultiplemethodcalls,thenthecurrentlineofcodewillreturntothatlineofcodeinthe callerandthenexecutionwilladvanceintothenextmethodtobecalled,orifthecurrentmethodwasthe lastmethodtobecalled,thecurrentlineofcodewillbethenextlineofcodeinthecaller. StepOver :Whenexecutionhasstoppedonalineofcode,clickingonthe StepOver buttoninthe debuggingpaneorselectingthemenuitem Debugger/StepOver orpressing F11 willcausethecurrent lineofcodetobeexecuted.ThisisverysimilartoStepInto,butifthetheexecutionwill notstop inside ofanymethodscalledinthecurrentlineofcode.Thusthenewcurrentlineofcodewillalwaysbeinthe PAGE 129 123 samemethod,unlesstheexecutedlinewasthelastlineinthemethod,uponwhichexecutionwillstopinthe callingmethodasusual.Thisfeatureisveryusefulwhenyouarecondentthatthemethodsbeingcalled workproperlyandyouarenotinterestedintheirdetailedexecution. StepOut :Whenexecutionhasstoppedonalineofcode,clickingonthe StepOut buttoninthe debuggingpaneorselectingthemenuitem Debugger/StepOut orpressing Shift+F12 willcausethe executiontoresumeuntilthecurrentmethodexits.Excutionwillstopatthenextexecutablelineinthe callingmethod .Thisisveryusefultoquicklyexitamethodwhosedetailedexecutionnolongerinterests youforinstance,ifyouaccidentallysteppedintoamethodthatyouwantedtostepover. ResumeDebugging :Whenexecutionhasstoppedonalineofcode,clickingonthe Resume buttonin thedebuggingpaneorselectingthemenuitem Debugger/ResumeDebugging orpressing F7 willcause theprogramexecutiontoresumeandcontinueuntilthenextbreakpointisencountered.Thisisusefulwhen youarenolongerinterestedinthedetailedexecutionofthecodeuntilthenextbreakpoint. Watches :Watchesareusedwhenyouwanttocontinuouslymonitorthevalueofaparticularvariable. SimplytypethenameofthevariableoreldintotheWatchpaneandwhencodeexecutionhaspaused,if thatvariablenameisinscope,itsvaluewillbedisplayed. Stack :Thestackcontainsanorderedlistofallmethodswithpendingoperationsatanygivenpointofa program'sexecution.Thatis,whentheprogramexecutionhasstoppedataparticularlineofcode,thestack containsthemethodthatlineofcodeisin,themethodthatcalledthatmethod,themethodthatcalled thatmethod,etc.InDrJava,the Stack tabwillshowthestackwiththecurrentmethodatthetopand thecallingmethodbelowit.Lookingatthestackisveryusefulfordeterminingwhereinyourprogramyou actuallyare,asoftenamethodiscalledfromlocationsthatareunintendedoronediscoversthatamethod isnotbeingcalledfromwhereyouwishittobecalled. Threads :AJavaprogramrunonmanysimultaneousexecutionpathsor"threads",eachperforming dierenttasksnecessaryforthetotaloperationofaJavaapplication.Asimpleprogramwrittenbya programmermayhaveasinglethreadthatrunsthecodewrittenbythatprogrammer,butmayalsohave manyotherthreadsperformingsuchtasksasmanagingthegraphicaluserinterface" GUI "ormanaging thememoryallocatedtotheprogram.Itisalsopossibleforaprogrammertowritecodethatutilizesmultiple threadsofexecutiontoaccomplishthedesiredgoals.The Threads tabismostusefulfordebuggingthese multi-threadedprogramsbyenablingthedevelopertobetterunderstandwhichthreadsareaccessingwhich objects. 7.2UnitTestingwithJUnitinDrJava 3 Objectorientedsystemsderivegreatcomplexitythroughtheinteractionsbetweentheobjectsinthesystem. Itisoftenimpossibletotesttheentirerangeofthetotalcomplexbehaviorthatasystemisdesignedto exhibit.Whatonecansayhoweveristhatifanygivenpartofthesystemdoesnotperformasdesired,then onecanmakenoassuranceswhatsoeverabouttheintegrityofthesystemasawhole.Thusthetestingof thesesmallerparts,or"units"isacrucialelementofdevelopinganylarge-scaleOOsystem.A unittest is a complete testofasmall,atomicsub-system.Notethatthisis not thesamefromapartialtestofsome aspectofthewholesystem! Unittestsareoftenperformedattheindividualclasslevel,meaningthatatestclassthatrunsallthe completebatteryoftestsonthetestedclass,iswrittenforeachclasstobetested.Insomecaseshowever, certainsystemsofclassesarenotdivisibleintoisolated,atomicunitsandinsuchmustbetestedasawhole. Thekeyistotestassmallapieceofthesystemaspossibleandtotestitasthoroughlyaspossible. 7.2.1UsingJUnitinDrJava Supposewehaveaclasssuchasthefollowingthatwewishtotest.Notethatclassis public andthatthe methodwewishtotestisalso public 3 Thiscontentisavailableonlineat PAGE 130 124 CHAPTER7.LABS SampleCodeToBeTested Figure7.1: Someexamplecodetobetested. InDrJava,select"File/NewJUnitTestCase...".Enteranamethatisdescriptiveofthetestsyou wishtomake.Arecommendationistousetheclassnamebeingtestedprependedwith" Test_ ",suchas Test_MyClass ".Thisenablesallyourtestclassestobeeasilyidentied,DrJavawillthenautomatically createavalidJUnittestclass,suchasbelow.NotethatDrJavadoesnotinitiallynamethenewclassle, butthedefaultnamesuggestedbyDrJavawhenyouattempttosaveitwillbecorrect. PAGE 131 125 AutogeneratedUnitTestClass Figure7.2: TestclassautogeneratedbyDrJava. Renametheauto-generated" testX "methodtosomethingmoredescriptiveoftheparticulartest you'dliketoperform.Thenewname must startwith" test "and must return void andtakenoinput parameters.Youcancreateasmanytestmethodsasyouwishtotestyourcode.JUnitwillautomatically runallmethodsthatbeginwith" test "astestmethods.Typically,asingletestmethodwilltestasingle methodontheclassundertest.Therearesituationshoweverwhereasinglemethodundertestmayrequire severaltestmethodstoproperlytestitsfullrangeofoperation.Inthecodethatfollows,the testX methodhasbeenrenamedto" test_myMethod1 ". 7.2.1.1assertEquals... Thereareanumberofwaysinwhichonecantestthattheproperresultisproduced.Thesimplestmethod istocompareasingleoutputvaluetoanexpectedvalue.Forinstance,supposeyouaretestingamethod thatreturnsaresult.Onecancomparetheactualreturnedvaluetothevalueoneexpectsforthegiven inputs.Therearetwomethodssuppliedbythejunit.framework.TestCaseclass,whichisthesuperclassofthe testclassgeneratedbyDrJava.Therstis voidassertEqualsStringfailResponse,Objectactual, Objectexpected .Theactualinputparameteristheactualresultofthemethodundertest.Theexpected parameteristheexpectedresult.failResponseisaStringthatJUnit/DrJavawilldisplayiftheactualvalue doesnot"equal"theexpectedvalue.The assertEquals... methodisoverriddensuchthatactualand expectedvaluescanbeeitherObjectsorprimitives. assertEquals... usesthe equals... method PAGE 132 126 CHAPTER7.LABS of Object tomakesitdetermination.Forprimitives,theusual == isused.Forinstance,wecouldwritethe testcasebelow.Iftheactualvaluedoesnotequaltheexpectedvalue, assertEquals throwsaexception thatiscaughtbytheJUnitframeworkandanerrormessagewillresult.Totestthecode,rstcompileall thecodethenselectthetestclass.Right-clickthetestclassandselect"TestCurrentDocument"orclick on"Tools/TestCurrentDocument."Thefollowingresultwillbedisplayed,giventhetestcodewewroteto purposelyfail: UsingassertEquals...inatestcase Figure7.3: assertEquals... displaystheerrorstringaswellascomparativeinformationifthe actual and expected valuesarenotequal. Asshownonthescreenshot,DrJavaclearlyindicatesinredthetestmethodthatfailedandthedierence betweentheexpectedandactualvalues.Italsohighlightsthelineofcodeinthetestmethodwherethe failureoccured. Thereisoneexceptiontothesyntaxof assertEquals ,andthatiswhenthevaluesbeingcomparedare doubles .Thisisbecauseround-oerrorsincalculatingoatingpointvaluesmeansthatitisalmostalways impossibletogeneratethesamevaluefromtwodierentcalculations,evenifmathematicallytheyarethe same.Forinstance,compate 2.3*2.3 and 5.29 .Mathematicallyidentical,butonaPCrunningWindows, Javacalculatesthemtobedierentbyapproximately 0.00000000000000089 or 8.9e-16 inJavasyntax. Thus,iftheexpectedandactualvaluesaretobeoftype double ,thena4'thinputparameterisrequired. PAGE 133 127 Thislastparameterisatolerancevalue,aplus-or-minusamountwithinwhichoneconsiderstheexpected andactualvaluestobeequal.Forinstance: assertEquals"Testingdoubles:5.29vs.2.3*2.3",5.29,2.3*2.3,9e-16; shouldpass,but assertEquals"Testingdoubles:5.29vs.2.3*2.3",5.29,2.3*2.3,8e-16; shouldfail.Notethatthetolerancevalueshouldalwaysbea positive value. 7.2.1.2assertTrue... Anothermethodprovidedby TestCase is voidassertTrueStringfailResponse,booleanresult Thisisasimpliedversionof assertEquals... usedwhentheresultcanbeexpressedasa boolean trueorfalse.Notethatanytestusing assertTrue canalsobewrittenas assertEqualsfailResponse, result,true. Forinstancewecouldwriteanothertestmethodtotestthe myMethod2 methodof MyClass .ThetestclassnowhastwotestmethodsandJUnitwillrunbothotthemwhenweclickon"Test CurrentDocument."Here,thesecondtestmethodpassesasshowningreenbelow.Therstmethodstill failsanditserrormessagesarestillshown.Clickingontheerrormessagewillhighlightthelinewherethe erroroccured.Correctingthecodein myMethod1... wouldresultinallthetestmethodsbeinglistedin greenwithnoerrormessages. PAGE 134 128 CHAPTER7.LABS UsingassertTrue...inatestmethod Figure7.4: assertTrue... isusedin test_myMethod2... aboveanddoesnotgenerateanerror becauseitisexecutedwithaboolean true value. 7.2.1.3fail... Formorecomplextesting, TestCase providesthe voidfailStringfailResponse method.Callingthis methodwillimmediatelycausethetestmethodtofailandthe failResponse stringwillbedisplayed.Since thismethoddoesnotknowtheactualorexpectedresults,the failResponse stringshouldcontainmore detailedinformationaboutwhatexactlyfailedandhowitfailed.Inthenextscreenshotisanexampleof using fail... wherethetestcodewaswrittensuchthatitwouldfail: PAGE 135 129 Usingfail...inatestmethod Figure7.5: The fail... methodimmediatelythrowsanerrorexceptionwhenitisexecuted. 7.2.1.4AdditionalCapabilities Notethatanytestmethodcancallothermethodsifneeded.Thisisusefulwhenthetestingprocedureis complexandneedstobebrokendownintosmallerpieces.Donotnamethesehelpermethodsstartingwith "test"ortheywillberunseparatelyastestcases!Usinghelpermethodsisalsousefulwhencertaintypesof testsareperformedonlyundercertainconditions. assertEquals... assertTrue... and fail... canbecalledfromanywhere,buttheDrJavawillonlyhighlightthelineinthemaintestmethodthat generatedtheerror,i.e.thelinethatcalledthehelpermethod.Itwillnothighlightthelineinthehelper methodwheretheactualcallto assertEquals... assertTrue... or fail... wasmade. Sometimesincomplextestingscenarios,thereisasignicantamountofinitializationworkrequiredto setupthesystemtobetested.Thisisoftenthecasewhentestingasystemofinterdependentobjectswhere theentiresystemmustbesetupbeforeanysingleobjectcanbetested.Iftheinitializationcodeisthe sameforallthetestsbeingconducted,themethod protectedvoidsetup canbedeclaredandbeused toexecutethenecessaryinitializations.Toinsure"clean"testruns,JUnit/DrJavare-instantiatesthetest classbeforerunningeachtestmethod.The setup method,ifitexists,iscalledbeforeanytestmethod isexecuted.Thismeansthatthetestclass cannot utilizeanyinternaleldvaluesthatonetestmethod modiesandanothertestmethodexpectstouseasmodied. Likewise,intheeventthatafteratestisrunthatsignicantamountsofcommon"clean-up"codeis PAGE 136 130 CHAPTER7.LABS required,onecandeclarethemethodprotectedvoid tearDown .Thismethodrunsaftereachtestmethod andisusefulforinsuring,forinstance,thatlesandnetworkconnectionsareproperlyclosedandthuskeep themfrominterferingwithothertests. ThehelpsysteminDrJavahasmoredetailedinformationontestingwithJUnit,includinghowtocreate atestsuiteofmultipletests. PAGE 137 Chapter8 Resources 8.1JavaSyntaxPrimer 1 ThismodulecontainsanassortmentoftopicscoveringJavasyntax.Itisnotintendedtobeacomplete tutorial. 8.1.1Constructors Aconstructorcanbethoughtofasaspecializedmethodofaclassthatcreatesinstantiatesaninstanceof theclassandperformsanyinitializationtasksneededforthatinstantiation.Thesytnaxforaconstructoris similarbutnotidenticaltoanormalmethodandadherestothefollowingrules: Thenameoftheconstructormustbeexactlythesameastheclassitisin. Constructorsmaybeprivate,protectedorpublic. Aconstructor cannot haveareturntypeeven void .Thisiswhatdistinguishesaconstructorfrom amethod.Atypicalbeginner'smistakeistogivetheconstructorareturntypeandthenspendhours tryingtogureoutwhyJavaisn'tcallingtheconstructorwhenanobjectisinstantiated. Multipleconstructorsmayexist,buttheymusthavedierentsignatures,i.e.dierentnumbersand/or typesofinputparameters. Theexistenceofanyprogrammer-denedconstructorwilleliminatetheautomaticallygenerated,no parameter, defaultconstructor .Ifpartofyourcoderequiresanoparameterconstructorandyou wishtoaddaparameterizedconstructor,besuretoaddanother,no-parameterconstructor. Example8.1 publicPerson{ privateString_name; publicPersonStringname{ _name=name; } 1 Thiscontentisavailableonlineat PAGE 138 132 CHAPTER8.RESOURCES } Theabovecodedenesapublicclasscalled Person withapublicconstructorthatinitializes the _name eld. Touseaconstructortoinstantiateaninstanceofaclass,weusethe new keywordcombinedwithan invocationoftheconstructor,whichissimplyitsnameandinputparameters. new tellstheJavaruntime enginetocreateanewobjectbasedonthespeciedclassandconstructor.Iftheconstructortakesinput parameters,theyarespeciedjustasinanymethod.Iftheresultantobjectinstanceistobereferencedby avariable,thenthetypeofthenewlycreatedobjectmustbeofthesametypeasthevariable.Notethat theconverseisnotnecessarilytrue!.Also,notethatanobjectinstancedoesnothavetobeassignedtoa variabletobeused. Example8.2 Personme=newPerson"Stephen"; Theabovecodeinstantiatesanew Person objectwhere _name eldhasthevalue" Stephen ". 8.2Connexions 8.2.1ViewingConnexionsContent 2 SeetheIntroductiontoConnexions 3 moduleforanoverviewofConnexions. 8.2.1.1SearchingtheContentCommons Youcansearchthe ContentCommons foraspecicmoduleoracourseusingthe Search buttonand textboxintheupperrightoftheConnexionswebpages.Typeinaname,keyword,coursetitle,module title,textstring,orobjectIDintheSearchtextboxandclick Search .Connexionswilldisplayalistofall modulesandcoursesthatmatchyourentry.Toviewamoduleorcourse,clickitstitle. 8.2.1.2OpeningaCollectionorCourse Selectthe"Content"tababovethe Youarehere BreadcrumbbartodisplaytheContentCommons Figure8.1screen.Thistaballowsyoutosearchformodulesorcoursesbytitle,authorname,orsubject area.Youcanalsodisplayalistingofallcontentbysubject,title,authorname,keyword,popularity,and morebyselectingtheappropriateitemunderthe"BrowseAllContent"headingonthetab. 2 Thiscontentisavailableonlineat PAGE 139 133 Figure8.1: ConnexionsCourses 8.2.1.3NavigatingWithinaCollectionorCourse Whenyourstopenacourse,thecoursetitlepagedisplays.Thispagecontainstwopanels.Onepanel displaysthe StartCourse linkandcourseinformation,suchastheinstitution,instructor,contributing authors,andabriefdescriptionofthecourse.Click StartCourse todisplaytheentirecourse,beginning withtherstmodule.Theotherpanelislabeled"CourseContents"anditcontainsatableofcontentsfor thecoursethatliststhenamesofthesectionsandmoduleswithinthatcourse.Youcanclickamodulename todisplaythatmodule. Onceyoudisplayamodulefromwithinacourse,youcanmovetothepreviousmoduleortothenext moduleinthecoursebyclickingthe PREV or NEXT linksthatappearintheupperrightcorner. PAGE 140 134 CHAPTER8.RESOURCES Figure8.2: Linkstothepreviousandnextmodulesinacourse note: The PREV and NEXT linksonlydisplaywhenyouaccessamodulefromwithinacourse. Ifyouaccessamoduledirectlyfromabrowser,theselinkstodonotappear. 8.2.1.4ViewingRelatedMaterial Youcanviewcontentrelatedtothemoduleyouaredisplayingusingthelinksinthe"RelatedMaterial" panelthatappearstotheleftofthemodulecontent.Thispanelincludes: Thenamesofothermodulesthatcontaincontentsimilartothecurrentmodule.Clickamodulename todisplaythatmodule. Anyothercoursesthatcontainthecurrentmodule.Clickacoursenametodisplaythatcourse. PAGE 141 135 Figure8.3: Linkstorelatedmaterial Inthepanelthatappearstotherightofthemodulecontentyoucanviewlinkstoexamples,supplemental material,orprerequisitematerialprovidedbythemoduleauthor.Theimportanceofthelinksareshownby thenumberofbarsintheboxtotheleftofthelinkname.TheselinkscanbetomaterialwithinConnexions ortoawebsiteoutsideofConnexions. PAGE 142 136 CHAPTER8.RESOURCES Figure8.4: Linkstopre-requisitematerials,supplementalmaterials,andexamplesnotshowninthis example 8.2.1.5DisplayingInformationabouttheModule Todisplaythe metadata forthemodule,clickthe Metadata linkattheendofthemodule.Metadataare non-contentinformationaboutamodule,suchasthemoduleID,licensetype,versionnumber,creationdate, revisiondate,authors,maintainers,copyrightholders,modulename,keywords,andabstract. 8.2.1.6ViewingModuleRevisionHistory Toviewtherevisionhistoryofamodule,clickthe VersionHistory linkattheendofthemodule.Whena newmoduleispublishedConnexionsassignsarevisionnumbertothatversionofthemodule.Ififbecomes necessarytoupdatethemodule,theauthorchecksitout,editsit,andpublishesitagain.Anincremented revisionnumberisassignedtotheupdatedversion.Connexionsstoresallthisrevisioninformationandyou canviewitontheHistorypageforthemodule. 8.2.1.7PrintingaModule TogenerateaPDFleofamodule,whichyoucanprint,clickthe PrintPDF linkthatappearsinthe upperleftcornerofthemoduleinthe"ContentActions"panel.Sometimesyoumaywantorneedaprinted copyofthematerialforstudyingpurposes.YoucangenerateaPDFleforanymodule.ThesePDFles areformattedforprintingwithpagenumbers,headers,footers,andnumberedheadings.Sincetheprinting processusesaPDFle,youmusthaveasoftwarepackagethatcanprintPDFlesinstalledonyourPC. PAGE 143 GLOSSARY 137 Glossary A AFrame.java packageview; importjavax.swing.*;//touseJFrame. /** *MinimalreusablecodetocreateaJFramewithatitleandawindowevent *listenertocallonSystem.exitandforceterminationofthemain *applicationthatcreatesthisJFrame. *@authorD.X.Nguyen */ publicabstractclassAFrameextendsJFrame{ publicAFrameStringtitle{ //Alwayscallthesuperclass'sconstuctor: supertitle; /** *AddananonymousWindowAdaptereventhandlertocallSystem.exitto *forceterminationofthemainapplicationwhentheFramecloses. *Withoutit,themainapplicationwillstillberunningevenafter *theframeisclosed. *Forillustrationpurpose,weusethefullpackagenamefor *WindowAdpaterandWindowEvent. *Wecouldhaveimportedjava.awt.event.*andavoidusingthefull *packagenames. */ addWindowListenernewjava.awt.event.WindowAdapter{ publicvoidwindowClosingjava.awt.event.WindowEvente{ System.out.printlne;//Forillustrationpurposeonly. System.exit; } }; /** *Subclassesaretodowhateverisnecessarytoinitializetheframe. *CAVEAT:Atrun-time,whenaconcretedescendantclassofAFrameis *created,onlytheconcreteinitializemethodofthisdescendant *classiscalled. */ initialize; } /** *Relegatestosubclassestheresponsibilitytoinitializethesystemto *awell-definedstate. */ protectedabstractvoidinitialize; } array Atitsmostbasicform,arandomaccess datastructurewhereanyelementcanbe accessedbyspecifyingasingleindex valuecorrespondingtothatelement. Example: anArray[4] givesus itemE Likewise,thestatement anArray[7]= 42 shouldreplace itemH with 42 assignment Tosetavariabletoaparticulardatavalue. B BinaryTree Amutablebinarytree, BiTree ,canbe inanemptystateoranon-emptystate: Whenitisempty,itcontainsno data. Whenitisnotempty,itcontainsa dataobjectcalledtherootelement, and2distinct BiTree objectscalled theleftsubtreeandtherightsubtree. C Class 1.Anabstractdenitionofasetofrelated objects.Aclassdenitionspeciesallthe invariantbehaviorsandotherattributes commontoalltheobjectsintheset. 2.InJava,thekeyword class denotesthe beginningofaclassdenition. D Denitionspane ThepaneattheupperrightoftheDrJava windowwhereoneeditsclassdenitions. PAGE 144 138 GLOSSARY F Frame2.java packageview; importjava.awt.*;//touseContainer. importjava.awt.event.*;//touseWindowAdpaterandWindowEvent. importjavax.swing.*;//touseJFrame. /** *AsubclassofAFramecontainingtwoJButtonsthathaveeventhandlercalled *"commands"todynamicallyswitchlayoutmanagerswhenthebuttonsareclicked *upon. *@authorD.X.Nguyen */ publicclassFrame2extendsAFrame{ publicFrame2Stringtitle{ supertitle; } protectedvoidinitialize{ Containercp=getContentPane; cp.setLayoutnewFlowLayout; JButtonjb1=newJButton"GridLayout"; JButtonjb2=newJButton"FlowLayout"; cp.addjb1; cp.addjb2; pack; /** *Registersananonymouseventhandlerfortheclickingofbuttonjb1. *Whenjb1isclickedupon,thiseventhandlerwillrespondby *executingitsactionPerformed...method. */ jb1.addActionListenernewActionListener{ publicvoidactionPerformedActionEvente{ jb1Clickede; } }; /** *Sameastheabove. */ jb2.addActionListenernewActionListener{ publicvoidactionPerformedActionEvente{ jb2Clickede; } }; } /** *DynamicallychangestoaGridLayoutwith2rowsand1column. */ protectedvoidjb1ClickedActionEvente{ System.out.println"SetGridLayout..."; getContentPane.setLayoutnewGridLayout,1; validate;//forcesthisframetore-layout. } /** *DynamicallychangestoFlowLayout. */ protectedvoidjb2ClickedActionEvente{ System.out.println"SetFlowLayout..."; getContentPane.setLayoutnewFlowLayout; validate;//forcesthisframetore-layout. } } Frame2App.java packageapp; importjavax.swing.*; importview.*; publicclassFrame2App{ publicstaticvoidmainString[]args{ JFramef=newFrame2"AJFramewith2JButtonswitheventlisteners"; f.setVisibletrue; f.setSize00,100;//Guesswhatthisdoes! f.setLocation,200;//Guesswhatthisdoes! //Forcestheframetore-layoutitscomponents: f.validate; } } Frame3.java packageview; importjava.awt.*; importjava.awt.event.*; importjavax.swing.*; /** *SamefunctionalityasFrame2butusesanadapterinterfacetocommunicate *withtheoutsideworldinstead.Thisdesignallowsvaryingthecommunication *withtheoutsideworld.Howtheoutsideworldreactstotheeventsthat *happentotheviewisavariantbehavior! PAGE 145 GLOSSARY 139 *UsestheNull-ObjectPatterntoinitializetheadapteravoidingcheckingfor *null. *@authorDXN */ publicclassFrame3extendsFrame2{ //Initializestheadaptertoanullobject: privateIView2World_v2wAdapter=newIView2World{ publicObjectbutton1ClickedActionEvente{ returnnull;//doesnothing! } publicObjectbutton2ClickedActionEvente{ returnnull;//doesnothing! } }; publicFrame3Stringtitle{ supertitle; } publicvoidsetV2WAdapterIView2Worldv2w{ ifnull==v2w{ thrownewIllegalArgumentException"Argumentcannotbenull!"; } _v2wAdapter=v2w; } /** *Tells_v2wAdapterthebuttonclickeventhappensonjb1. */ protectedvoidjb1ClickedActionEvente{ _v2wAdapter.button1Clickede; } /** *Tells_v2wAdapterthebuttonclickeventhappensonjb2. */ protectedvoidjb2ClickedActionEvente{ _v2wAdapter.button2Clickede; } } Frame3App.java packageapp; importview.*; importcontroller.*; /** *Instantiatesthecontrollerandbuildstheframe! */ publicclassFrame3App{ publicstaticvoidmainString[]args{ newFrame3Controller.constructFrame.validate; } } Frame3Controller.java packagecontroller; importview.*; importjava.awt.event.*; importjavax.swing.JFrame; importjava.awt.*;//Forlayoutmanagers. /** *ThecontrollerthatinstantiatesaconcreteIView2Worldobjectandconnects *theworldoutsideofFrame3theviewtoFrame3. *Theconcreteadapterisimplementedasananonymousinnerclasse. */ publicclassFrame3Controller{ publicJFrameconstructFrame{ //Localvariableneedstobefinalsothatthelocalinnerclass //canaccessit: finalFrame3frame=newFrame3"ViewandController"; /** *InstallasconcreteanonymousIView2Worldadapterinframe,without *frameknowingwhattheadapterdoes. */ frame.setV2WAdapternewIView2World{ publicObjectbutton1ClickedActionEvente{ frame.getContentPane.setLayoutnewGridLayout,1; frame.validate; returnnull; } publicObjectbutton2ClickedActionEvente{ frame.getContentPane.setLayoutnewFlowLayout; frame.validate; returnnull; } }; frame.setVisibletrue; returnframe; } } PAGE 146 140 GLOSSARY FrameA.java packageview; /** *AdirectconcretesubclassofAFramewithitsowninitializaioncode. */ publicclassFrameAextendsAFrame{ /** *CallsAFrameconstructor,whichcallsthecocnreteinititializemethod *ofthisFrameA.Thisisdonedynamicallyatrun-timewhenaFrameA *objectisinstantiated. */ publicFrameAStringtitle{ supertitle; } /** *Thesuperclassinitializemethodisabstract:don'tcallithere! *JustwriteapplicationspecificinitializationcodeforthisFrameAhere. */ protectedvoidinitialize{ //ApplicationspecificintializationcodeforFrameAgoeshere... } } FrameAB.java packageview; /** *AsecondleveldescendantclassofAFrame *thatinitializesitselfbycallingthe *initializemethodofitsdirectsuperclass *inadditiontoitsowninitializationcode. */ publicclassFrameABextendsFrameA{ /** *Callsthesuperclassconstructor,FrameA, *whichinturnscallsitssuperclassconstructor, *AFrame,whichfirstcallsitssuperclass *constructor,JFrame,andthenexecutesthe *initializemethodofthisFrameAB. */ publicFrameABStringtitle{ supertitle; } /** *Atrun-time,whentheconstructorAFrameis *executed,itcallsthisFrameABinitialize *methodandNOTtheinitializemethodofthe *superclassFrameA.Inordertoreusethe *initializationcodeforFrameA,wemustmake *thesupercalltoinitialize. */ protectedvoidinitialize{ //CallinitializeofFrameA: super.initialize; /** *Additionalapplicationspecificintialization *codeforFrameABgoeshere... */ } } FrameAC.java packageview; /** *AsecondleveldescendantclassofAFrame *thatbypassestheinitializemethodof *itsdirectsuperclassinitsown *initializationcode.Sinceproper *initializationofasubclassdependson *properinitializationofthesuperclass, *bypassingtheinitializationcodeofthe *superclassisaBADidea! */ publicclassFrameACextendsFrameA{ /** *Callsthesuperclassconstructor,FrameA, *whichinturnscallsitssuperclassconstructor, *AFrame,whichfirstcallsitssuperclass *constructor,JFrame,andthenexecutesthe *initializemethodofthisFrameAC. */ publicFrameACStringtitle{ supertitle; } /** PAGE 147 GLOSSARY 141 *Atrun-time,whentheconstructorAFrameis *executed,itcallsthisinitializemethodand *NOTtheinitializemethodofthesuperclass *FrameA.Thismethoddoesnotcallthesuper *class'sinitializemethod.Asaresult,the *initializationdoneinthesuperclassis *bypassedcompletely.ThisisaBADidea! */ protectedvoidinitialize{ /** *Applicationspecificintializationcodefor *FrameACgoeshere... */ } } I Instantiate Tocreateanobjectbasedonthe specicationsdenedinaclassdenition. Theobjectcreatediscalledan instance ofthatclass. Interactionspane ThepaneattheloweredgeoftheDrJava windowwhereonecaninteractively executeJavastatements. invariant Thepartsofaprobram,suchasvaluesor programmaticbehaviors,thatdonot varyfromoneinvocationtothenext. Notethatwhileavaluemaybevariant, anabstractionofthatvaluemaybe invariant. IView2World.java packageview; importjava.awt.event.*; /** *AdapterconnectingFrame3theViewtotheoutsideworld. */ publicinterfaceIView2World{ /** *CalledbyFrame3whenitsbutton1isclicked. */ publicObjectbutton1ClickedActionEvente; /** *CalledbyFrame3whenitsbutton2isclicked. */ publicObjectbutton2ClickedActionEvente; } L literal Anexplicit,concretetextual reprepresentationofavalueofagiven type.Literalsareoftenusedtosetthe valuesforvariables. T type Asetofvalueswithcertaincommon characteristics.InJava,alldatavalues mustbeofsometype. Example: int isatypethatisusedto representintegernumbervalues. double isatypethatisusedtorepresentreal numbervalues. String isatypethatis usedtorepresentastringofcharacters. U UML UniedModelingLanguage,developedby theObjectManagementGroup"OMG" UnitTest Thetestingofasingleclassorsmall collectionofclassesa"unit"toverify correctbehavioratane-grainedlevel. V variable Amemorylocationtoholdaparticular valueofagiventype.Inastrongly-typed languagesuchasJava,allvariablesmust haveatype.Thisisnottrueinall languageshowever.InaJavaprogram, variableshavenamescalledindentiers, whicharesequencesofcharactersput togetheraccordingtothefollowingrule. Amustbeginwithanalphabetcharacter e.g.'a','b','X','Y',etc.andmaybe followedbyzeroormorealphabet charactersand/ordigitcharacterse.g. '0','1',etc.and/ortheunderscore character'_'.Forexamples,cp3POisa validvariablenamewhileDarthVaderis notbecauseithasablankcharacter betweenthe'h'andthe'V'. variant PAGE 148 142 GLOSSARY Thepartsofaprogram,suchasvaluesor programmaticbehaviors,thatvaryfrom oneinvocationtothenext.Notethat whileavaluemaybevariant,its abstractionmaybeinvariant. PAGE 149 INDEX 143 IndexofKeywordsandTerms Keywords arelistedbythesectionwiththatkeywordpagenumbersareinparentheses.Keywords donotnecessarilyappearinthetextofthepage.Theyaremerelyassociatedwiththatsection. Ex. apples,1.1 Terms arereferencedbythepagetheyappearon. Ex. apples,1 A abstract,2.3,3.4,77 AbstractBehavior,79 abstractclasses,2.221 AbstractConstruction,79 AbstractEnvironments,79 AbstractFactoryDesignPattern,63 AbstractFactoryPattern,57 AbstractStructure,79 abstractionlayers,1.1 accessspecier,5 AFrame,113,114,114,115 Algorithm,3.3 algorithms,4.3 annotation,8.2.1 anonymous,3.5 Applet,6.1 applets,113 array,97,97 arrayprocessing,4.4 arrays,4.4 B Ballworld,2.2,2.3 behavioralabstraction,1.1 BinaryTree,93 binarytrees,4.3 breakpoints,122,122 C change,4.2 char,2 class,1.2 classes,6,2.3 ClearAllBreakpoints,122 closure,3.5,76,77 codelisting,114 command,6.2,117 commanddesignpattern,6.2 component,3.4 composite,3.1 compositedesignpattern,40 composition,2.3 Composition"has-a"lines,12 constructor,5 ContentCommons,132 D dataabstraction,1.1 DebuggingMode,122 decorator,31 decoree,31 Decoupling,3.3 delegates,27 dequeue,105 design,2.3,3.1,3.2, 3.3,3.4,4.1 designpatterns,OOP,objectoriented programming,polymorphism,inheritance, 2.1 double,2 dynamic,4.1 dynamicreclassication,4.2 E elements,98 encapsulated,40 enqueue,105 eventlisteners,78 F factory,3.4 elds,5,6 FIFOFirstInFirstOut,105 nal,77 foreach,4.4 forloop,4.4,99 for-eachloop,103 Frame2,117 Frame2.java,117 Frame3,117 Frame3.java,117 Frame3Controller,117 FrameA,114,115 FrameAB,114,116 FrameAC,114,116 framework,3.4,89 G graphicaluserinterface,6.1,113 gui,6.1,113,6.2,123 PAGE 150 144 INDEX guiprogramming,6.1 H helpers,3.5 hiding,3.4 hook,91 I Implementation"acts-like-a"lines,11 implements,10 indirectionlayer,31 information,3.4 inherit,9 inheritance,16,2.2,2.3 Inheritance"is-a"lines,9 Inheritance,composition,aggregation, abstraction,objectorientedprogramming, objectorienteddesign,OOP,OOD,1.3 inner,3.5 innerclass,77 int,2,4 interface,10 Interpreter,3.2 interpreterdesignpattern,42 invariant,1,114 isomorphic,38,40 IView2World,119 J Java,1.2,4.3,4.4,5.2, 6.1,6.2 javagui,6.1,6.2117 javaguiprogramming,6.2 Java,syntax,objectorientedprogramming, 8.1 JFrame,6.1 K keyword,6 L lamdba,78 layoutmanager,116 levelsofabstraction,19 LIFOLastInFirstOut,105 linearrecursivestructure,4.2 list,3.1,3.2 locate,8.2.1 M members,77 metadata,136 method,3 methods,6 mutation,4.2 N nested,3.5 nestedclass,77 new,3 notes,8.2.1 nullobject,118 null-objectpattern,6.2 O object,1.2,2.3,5.1 objectoriented,5.2 objectorienteddesign,2.2 objectorientedprogramming,2.2 object-oriented,3.5 object-orientedprogramming,1.2 objects,5 on-the-y,3.5 OO,3.5 OOD,2.2,2.3,5.2 OOP,1.2,2.2,2.3,3.1, 3.5,5.2 ordering,5.2 oriented,2.3 orientedprogramming,5.1 overriding,24 P package,77 Parnas,3.4 pattern,3.1,3.2,3.3, 3.4,4.1 polymorphism,10,16,2.2,2.3 priority,5.2 private,63,77 privatestatic,60 proceduralabstraction,1.1 programming,2.3,5.2,6.2 protected,77 public,5,77 Q queue,5.2 R RAC,5.1,5.2 reclassication,4.1 recursion,40 recursive,38 restrictedaccesscontainer,5.2 ResumeDebugging,123 S separationofvariantandinvariantbehaviors, 25 softwarecomponent,58 spyobjects,79 Stack,122,123 state,4.1,4.2 statedesignpattern,4.2 static,63 statictyping,35 StepInto,122 PAGE 151 INDEX 145 StepOut,123 StepOver,122 strategy,6.1 strategypattern,6.1 Structure,3.3 structures,4.3 student,8.2.12 subclass,9 superclass,9 T template,6.1 templatemethod,6.1 templatemethodpattern,6.1 Threads,122,123 tree,93 type,1,6 U UML,classdiagrams,object-orienteddesign, OOD,1.4 UnionDesignPattern,16 unittest,123 unittesting,JUnit,DrJava,OOP,OOD, objectorientedprogramming,objectoriented design,7.2 V variant,1 view,8.2.1 Visitor,3.3 visitordesignpattern,4.2 visitors,4.3 W Watch,122 Watches,123 whileloop,4.4 PAGE 152 146 ATTRIBUTIONS Attributions Collection: PrinciplesofObject-OrientedProgramming Editedby:StephenWong,DungNguyen URL:http://cnx.org/content/col10213/1.31/ License:http://creativecommons.org/licenses/by/1.0 Module:"Abstraction" By:StephenWong,DungNguyen URL:http://cnx.org/content/m11785/1.21/ Pages:1-5 Copyright:StephenWong,DungNguyen License:http://creativecommons.org/licenses/by/1.0 Module:"ObjectsandClasses" By:StephenWong,DungNguyen URL:http://cnx.org/content/m11708/1.6/ Pages:5-8 Copyright:StephenWong,DungNguyen License:http://creativecommons.org/licenses/by/1.0 Module:"ObjectRelationships" By:StephenWong,DungNguyen URL:http://cnx.org/content/m11709/1.5/ Pages:9-12 Copyright:StephenWong,DungNguyen License:http://creativecommons.org/licenses/by/1.0 Module:"UMLDiagrams" By:StephenWong,DungNguyen URL:http://cnx.org/content/m11658/1.3/ Pages:12-15 Copyright:StephenWong,DungNguyen License:http://creativecommons.org/licenses/by/1.0 Module:"UnionDesignPattern:InheritanceandPolymorphism" By:StephenWong,DungNguyen URL:http://cnx.org/content/m11796/1.11/ Pages:15-21 Copyright:StephenWong,DungNguyen License:http://creativecommons.org/licenses/by/1.0 Module:"Ballworld,inheritance-based" By:StephenWong,DungNguyen URL:http://cnx.org/content/m11806/1.7/ Pages:21-26 Copyright:StephenWong,DungNguyen License:http://creativecommons.org/licenses/by/1.0 PAGE 153 ATTRIBUTIONS 147 Module:"Ballworld,composition-based" By:StephenWong,DungNguyen URL:http://cnx.org/content/m11816/1.5/ Pages:27-34 Copyright:StephenWong,DungNguyen License:http://creativecommons.org/licenses/by/1.0 Module:"ListStructureandtheCompositeDesignPattern" By:StephenWong,DungNguyen URL:http://cnx.org/content/m15111/1.1/ Pages:37-41 Copyright:StephenWong,DungNguyen License:http://creativecommons.org/licenses/by/2.0/ Module:"ListStructureandtheInterpreterDesignPattern" By:DungNguyen URL:http://cnx.org/content/m15110/1.1/ Pages:41-43 Copyright:DungNguyen License:http://creativecommons.org/licenses/by/2.0/ Module:"VisitorDesignPattern" By:DungNguyen URL:http://cnx.org/content/m16707/1.1/ Pages:43-55 Copyright:DungNguyen License:http://creativecommons.org/licenses/by/2.0/ Module:"AbstractFactoryDesignPattern" By:DungNguyen URL:http://cnx.org/content/m16796/1.1/ Pages:55-64 Copyright:DungNguyen License:http://creativecommons.org/licenses/by/2.0/ Module:"InnerClasses" By:StephenWong,DungNguyen URL:http://cnx.org/content/m17220/1.1/ Pages:64-83 Copyright:StephenWong,DungNguyen License:http://creativecommons.org/licenses/by/2.0/ Module:"StateDesignPattern" By:DungNguyen URL:http://cnx.org/content/m17225/1.3/ Pages:85-87 Copyright:DungNguyen License:http://creativecommons.org/licenses/by/2.0/ Module:"MutableLinearRecursiveStructure" By:DungNguyen URL:http://cnx.org/content/m17265/1.1/ Pages:87-93 Copyright:DungNguyen License:http://creativecommons.org/licenses/by/2.0/ PAGE 154 148 ATTRIBUTIONS Module:"BinaryTreeStructure" By:StephenWong,DungNguyen URL:http://cnx.org/content/m17289/1.2/ Pages:93-97 Copyright:StephenWong,DungNguyen License:http://creativecommons.org/licenses/by/2.0/ Module:"ArraysandArrayProcessing" By:StephenWong,DungNguyen URL:http://cnx.org/content/m17258/1.2/ Pages:97-104 Copyright:StephenWong,DungNguyen License:http://creativecommons.org/licenses/by/2.0/ Module:"RestrictedAccessContainers" By:StephenWong URL:http://cnx.org/content/m17101/1.1/ Pages:105-112 Copyright:StephenWong License:http://creativecommons.org/licenses/by/2.0/ Module:"OrderingObjectandPriorityQueue" By:StephenWong URL:http://cnx.org/content/m17064/1.1/ Page:112 Copyright:StephenWong License:http://creativecommons.org/licenses/by/2.0/ Module:"GraphicalUserInterfacesinJava" By:StephenWong,DungNguyen URL:http://cnx.org/content/m17185/1.3/ Pages:113-116 Copyright:StephenWong,DungNguyen License:http://creativecommons.org/licenses/by/2.0/ Module:"MoreJavaGUIProgramming" By:StephenWong,DungNguyen URL:http://cnx.org/content/m17186/1.2/ Pages:117-119 Copyright:StephenWong,DungNguyen License:http://creativecommons.org/licenses/by/2.0/ Module:"DrJava" By:StephenWong,DungNguyen URL:http://cnx.org/content/m11659/1.5/ Pages:121-123 Copyright:StephenWong,DungNguyen License:http://creativecommons.org/licenses/by/1.0 Module:"UnitTestingwithJUnitinDrJava" By:StephenWong,DungNguyen URL:http://cnx.org/content/m11707/1.4/ Pages:123-130 Copyright:StephenWong,DungNguyen License:http://creativecommons.org/licenses/by/1.0 PAGE 155 ATTRIBUTIONS 149 Module:"JavaSyntaxPrimer" By:StephenWong,DungNguyen URL:http://cnx.org/content/m11791/1.1/ Pages:131-132 Copyright:StephenWong,DungNguyen License:http://creativecommons.org/licenses/by/1.0 Module:"ViewingConnexionsContent" By:MarkHusband URL:http://cnx.org/content/m11837/1.13/ Pages:132-136 Copyright:MarkHusband License:http://creativecommons.org/licenses/by/1.0 PAGE 156 PrinciplesofObject-OrientedProgramming Anobjects-rstwithdesignpatternsintroductorycourse AboutConnexions Since1999,Connexionshasbeenpioneeringaglobalsystemwhereanyonecancreatecoursematerialsand makethemfullyaccessibleandeasilyreusablefreeofcharge.WeareaWeb-basedauthoring,teachingand learningenvironmentopentoanyoneinterestedineducation,includingstudents,teachers,professorsand lifelonglearners.Weconnectideasandfacilitateeducationalcommunities. Connexions'smodular,interactivecoursesareinuseworldwidebyuniversities,communitycolleges,K-12 schools,distancelearners,andlifelonglearners.Connexionsmaterialsareinmanylanguages,including English,Spanish,Chinese,Japanese,Italian,Vietnamese,French,Portuguese,andThai.Connexionsispart ofanexcitingnewinformationdistributionsystemthatallowsfor PrintonDemandBooks .Connexions haspartneredwithinnovativeon-demandpublisherQOOPtoacceleratethedeliveryofprintedcourse materialsandtextbooksintoclassroomsworldwideatlowerpricesthantraditionalacademicpublishers. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| MILLISECOND | CLASS.METHOD | MESSAGE |
|---|---|---|
| 0 | sobekcm_page_globals.constructor | |
| 0 | sobekcm_page_globals.constructor | Application State validated or built |
| 0 | sobekcm_database.verify_item_lookup_object | |
| 0 | sobekcm_page_globals.constructor | Navigation Object created from URI query string |
| 0 | sobekcm_database.verify_item_lookup_object | |
| 0 | sobekcm_page_globals.display_item | Retrieving item or group information |
| 0 | sobekcm_page_globals.get_entire_collection_hierarchy | Retrieving hierarchy information |
| 0 | sobekcm_assistant.get_entire_collection_hierarchy | |
| 0 | cached_data_manager.retrieve_item_aggregation | |
| 0 | cached_data_manager.retrieve_item_aggregation | Found item aggregation on local cache |
| 0 | item_aggregation_builder.get_item_aggregation | Found 'all' item aggregation in cache |
| 0 | system.web.ui.page.page_load (ufdc.page_load) | |
| 0 | sobekcm_page_globals.constructor.on_page_load | |
| 0 | html_echo_mainwriter.add_style_references | Adding style references to HTML |
| 0 | html_echo_mainwriter.add_text_to_page | Reading the text from the file and echoing back to the output stream |
| 88 | html_echo_mainwriter.add_text_to_page | Finished reading and writing the file |