Sie sind auf Seite 1von 29

JavaFoundations:IntroductiontoProgramDesign&DataStructures JohnLewis,PeterJ.

DePasquale,JosephChase TestBank:Chapter5

Chapter1:Introduction MultipleChoiceQuestions:
1)A________________diagramhelpsusvisualizethecontentsofandrelationshipsamongtheclassesofaprogram. a)classandobject b)UML c)objectoriented d)public e)private Answer:b Explanation:AUMLdiagramhelpsusvisualizethecontentsandrelationshipsamongtheclassesofaprogram. Theotherchoicesdonotrefertoanytypeofdiagram. 2)Whichofthefollowingobjectorientedprinciplesreferstothefactthatanobjectshouldhaveitsdataguardedfrom inappropriateaccess? a)encapsulation b)inheritance c)polymorphism d)instancevariables e)methods Answer:a Explanation:Encapsulationistheobjectorientedprinciplethatspecifiesthatanobjectsdatashouldbeguarded frominappropriateaccess.Thereforechoiceaiscorrect.Inheritanceandpolymorphismarefeaturesofobjectoriented programmingthatallowforclassflexibilityandreuse.Instancevariablesandmethodsplayimportantrolesinobject orientedprogramming,butarenotfundamentalprinciples. 3)Whenappliedtoinstancevariables,the________________visibilitymodifierenforcesencapsulation. a)static b)final c)public d)private e)noneoftheabove Answer:d Explanation:Theprivatevisibilitymodifierguardsagainstinappropriatedataaccess,andthereforepromotes encapsulation.Choicesaandbarenotvisibilitymodifiers,andchoicecisavisibilitymodifierthatallowspublicaccessto anobjectsdata,whichviolatestheprincipleofencapsulation. 4)Whichofthefollowingtypesofmethodsdonothaveanyreturntype(notevenavoidreturntype)? a)methodsdeclaredasstatic 1 AddisonWesley2007

JavaFoundations:IntroductiontoProgramDesign&DataStructures JohnLewis,PeterJ.DePasquale,JosephChase TestBank:Chapter5 b)methodsdeclaredaspublic c)methodsdeclaredasprivate d)constructors e)alloftheabovehavereturntypes Answer:d Explanation:Constructorsaretheonlymethodsthatdonothaveanyreturntype.Theydonotevenhaveavoid returntype.Alloftheothermethodsmustspecifyareturntypeorbedeclaredasvoid. 5)Whichofthefollowingmethodheadersismostlikelyaheaderforamutatormethod? a)publicintgetAge() b)publicdoublecomputeSalary() c)publicPerson() d)publicvoidsetAge(intnewAge) e)noneoftheseareheadersforamutatormethod Answer:d Explanation:Mutatorsaremethodsthatchangethevalueofaninstancevariable,andareoftenreferredtoas setters.Therefore,choicedisthecorrectanswer.Choiceaisanexampleofaheaderforaaccessormethod,often referredtoasagetter.Choicecisaconstructor,andchoicebisaclassmethod. 6)A_______________variableissharedamongallinstancesofaclass. a)static b)final c)public d)private e)noneoftheabove Answer:a Explanation:Astaticvariableissharedamongallinstancesofaclass.Afinalvariableisaconstant,apublic variableisonethatisaccessiblefromoutsidetheobjectandaprivatevariableisonethatcannotbeaccessedoutsideof theobject. 7)__________________parametersarethevaluesthatareusedwhencallingamethod. a)formal b)actual c)useful d)informal e)noneoftheabove Answer:b Explanation:Actualparametersaresentinwhencallingamethod.Formalparametersareusedwhendefininga

method.

8)The________________referencealwaysreferstothecurrentlyexecutingobject. 2 AddisonWesley2007

JavaFoundations:IntroductiontoProgramDesign&DataStructures JohnLewis,PeterJ.DePasquale,JosephChase TestBank:Chapter5

a)null b)static c)final d)actual e)this Answer:e Explanation:Thethisreferencealwaysreferstothecurrentlyexecutingobject.Anullreferenceisareference thatisnotpointingtoanyobject.TheotherthreechoicesarenotspecialreferencesinJava. 9)Amethodthathasmultipledefinitionsisan__________________method. a)overloaded b)overridden c)overlooked d)overclocked e)noneoftheabove Answer:a Explanation:Amethodthathasmultipledefinitionsisanoverloadedmethod.Theversionsofanoverloaded methodaredistinguishedbythenumber,typeandorderoftheirparameters.Overriddenmethodsaremethodsthathave beenredefinedlaterinaninheritancehierarchy.Theywillbestudiedinmoredetaillater.Choicecanddarenottypesof methodsinJava. 10)A(n)________________isastepbystepprocessforsolvingaproblem. a)UMLdiagram b)aggregateobject c)class d)algorithm e)noneoftheabove Answer:d Explanation:Analgorithmisastepbystepsolutionforsolvingaproblem.AUMLdiagramisawayofvisually representinghowclassesandobjectsinteract.Anaggregateobjectisanobjectthatiscomposed,inpart,ofotherobjects.A classcanbethoughtofasablueprintforasetofobjects. 11)Allmethods(withtheexceptionofconstructors)mustspecifyareturntype.Whatisthereturntypeforamethodthat doesnotreturnanyvalues? a)int b)public c)double d)void e)noneoftheabove Answer:d 3 AddisonWesley2007

JavaFoundations:IntroductiontoProgramDesign&DataStructures JohnLewis,PeterJ.DePasquale,JosephChase TestBank:Chapter5 Explanation:Methodsthatdonotneedtoreturnanydatashouldhavevoidspecifiedasthereturntype.A methodcannothavepublicspecifiedasitsreturntype,sochoicebisincorrect.Choiceaandchoicecspecifyareturn type,andthereforetheymustreturndataofthattype. 12)Methodsthatcanbecalleddirectlythroughtheclassnameanddonotneedtohaveanobjectinstantiatedarecalled _________________. a)final b)public c)static d)private e)noneoftheabove Answer:c Explanation:Methodsthatcanbecalleddirectlythroughtheclassnamemustbedeclaredasstatic.Choiceb andchoicedarevisibilitymodifiersforamethod.Methodsdeclaredasfinalcannotbeoverridden. 13)A(n)___________________objectisonethatismadeup,atleastinpart,ofotherobjects. a)static b)aggregate c)encapsulated d)private e)public Answer:b Explanation:Anaggregateobjectisonethatismadeupofotherobjects.Choicea,dandedonotrefertotypesof objects.Encapsulatedobjectsmaybemadeupofprimitivetypesorobjecttypes. 14)Ifaserviceissocomplexthatitcannotbereasonablybeimplementedusingonemethod,itisoftenhelpfulto decomposeittomakeuseof________________supportmethods. a)static b)aggregate c)private d)public e)final Answer:c Explanation:Privatesupportmethodsareusefulwhenaserviceistoocomplextobedefinedinasinglemethod. Thereforechoicediscorrect. 15)Theversionsofanoverloadedmethodaredistinguishedby___________________________. a)thenumber,typeandorderoftheirparameters b)theiridentifiers c)theirclasses d)thenumberandtypeoftheirparameters 4 AddisonWesley2007

JavaFoundations:IntroductiontoProgramDesign&DataStructures JohnLewis,PeterJ.DePasquale,JosephChase TestBank:Chapter5 e)thenumberoftheirparameters Answer:a Explanation:Overloadedmethodsaretwomethodsinthesameclassthathavethesameidentifier,butadifferent number,typeororderofparameters.Therefore,choiceaiscorrectandtherestareincorrect.

5 AddisonWesley2007

JavaFoundations:IntroductiontoProgramDesign&DataStructures JohnLewis,PeterJ.DePasquale,JosephChase TestBank:Chapter5

True/FalseQuestions:
1)Avariablecanalwaysbereferencedanywhereinaprogram. Answer:False Explanation:Thescopeofavariabledetermineswhereitcanbereferenced.Itdependsonwherethevariableis declared. 2)Anobjectcanbethoughtofasablueprintforasetofclasses. Answer:False Explanation:Aclasscanbethoughtofasablueprintforasetofobjects;nottheotherwayaround. 3)Areturnstatementisnotrequiredattheendofeverymethod. Answer:True Explanation:Areturnstatementisnotrequiredattheendofaconstructororanymethoddeclaredwiththereturn typevoid. 4)Whenanobjectispassedtoamethod,theactualandformalparametersbecomealiases. Answer:True Explanation:Actualparametersarethedatumthataresentintothemethod.Theformalparametersareusedinthe methoddefinition.Whenobjectsaresenttoamethod,bothofthesevaluesarereferences,andtheybecomealiasesofone another. 5)Therearetimeswhenitisappropriatetoreturndatafromamethodofatypethatisinconsistentwiththereturntype specifiedinthemethodheader. Answer:False Explanation:Thevaluereturnedfromamethodmustbeconsistentwiththereturntypespecifiedinthemethod header. 6)Amainmethodcanonlyaccessstaticorlocalvariables. Answer:True Explanation:Amainmethodcannotaccessnonstaticandnonlocalvariablesbecauseitisastatic method.Inparticular,itcannotaccessanyvariablesdeclaredattheclasslevel. 7)Inaclassthathasvariablescalledheightandwidth,methodscalledgetHeight()andgetWidth()are examplesofaccessormethods. Answer:True Explanation:Accessormethodsgetthevalueofinstancevariables.Incontrast,mutatorssetthevalues. 8)Aprogrammerisrequiredtodefineaconstructorforeveryclass. Answer:False Explanation:Everyclassautomaticallyhasadefaultconstructorthatdoesn'ttakeanyparameters. 9)Variablesthataredeclaredasstaticaresharedamongallinstancesofaclass. Answer:True Explanation:Staticvariablesaresometimescalledclassvariablesbecausetheyaresharedamongallinstancesofa class. 10)Aggregationissometimesdescribedasahasarelationship. 6 AddisonWesley2007

JavaFoundations:IntroductiontoProgramDesign&DataStructures JohnLewis,PeterJ.DePasquale,JosephChase TestBank:Chapter5 Answer:True Explanation:Aggregateobjectsaremadeupofotherobjects.Thereforetherelationshipbetweenanobjectthatis anaggregateofotherobjectsisoftendescribedasahasarelationship.

7 AddisonWesley2007

JavaFoundations:IntroductiontoProgramDesign&DataStructures JohnLewis,PeterJ.DePasquale,JosephChase TestBank:Chapter5

ShortAnswerQuestions:
1)Whatisthedifferencebetweenanobjectandaclass? class. Answer:Aclasscanbethoughtofastheblueprintforanobject.Inotherwords,theobjectistheembodimentofa

2)Explainthedifferencebetweenactualparametersandformalparameters. Answer:Formalparametersareusedinthedefinitionofamethod,whileactualparametersarethevaluesthatare usedinthemethodcall. 3)Whatisencapsulation?HowcanitbeenforcedinJava? Answer:Encapsulationistheprinciplethatobjectsshouldbeselfgoverning.Inotherwords,anobject'sinternal datashouldbeprotectedfromoutsideaccess.EncapsulationcanbeenforcedinJavabymakinginstancevariablesprivate. 4)WriteamethodcalledmaxOfThreethatacceptsthreeintegerparametersandreturnsthelargestofthethree. Answer: publicintmaxOfThree(intfirstInt,intsecondInt,intthirdInt){ if(firstInt>=secondInt&&firstInt>=thirdInt) returnfirstInt; elseif(secondInt>=firstInt&&secondInt>=thirdInt) returnsecondInt; else returnthirdInt; } 5)WriteamethodcalledrandomInRangethattakesintwonumbersrepresentingarange.Printanerrormessageand returnzeroifthesecondparameterislessthanthefirst.Otherwise,themethodshouldreturnarandomlygeneratedinteger inthatrange(inclusive).YoumayassumethattheclasshasastaticRandomobjectcalledgeneratoralreadydeclared andinstantiated. Answer: publicintrandomInRange(inta,intb){ if(b<a){ System.out.println(Error,invalidrange!); return0; } returngenerator.nextInt(ba+1)+a; } 6)WriteamethodcalledisPalindromethatacceptsaStringasaparameterandreturnstrueiftheStringisa palindrome,andfalseotherwise.YoumayassumethattheenteredStringconsistsentirelyoflowercaseletters(meaningit 8 AddisonWesley2007

JavaFoundations:IntroductiontoProgramDesign&DataStructures JohnLewis,PeterJ.DePasquale,JosephChase TestBank:Chapter5 containsnonumbers,spaces,punctuation,etc).Hint:writecodethatcreatesanewstringthatistheoriginalstring reversed,andthenchecktoseeifthetwostringsareequal. Answer: publicbooleanisPalindrome(Strings){ StringreverseS=newString(); for(inti=s.length()1;i>=0;i) reverseS+=s.charAt(i); returnreverseS.equals(s); } 7)WriteamethodcalledcountSpacesthattakesinaStringasaparameterandreturnsanintegerthatrepresentsthe numberofspacecharacters('')containedinthestring,falseotherwise.. Answer: publicintcountSpaces(Strings){ intcount=0; for(inti=0;i<s.length();i++) if(s.charAt(i)=='') count++; returncount; } 8)WriteamethodcalledcontainsPairthattakesinthreeintegerparametersandreturnstrueifanytwooftheinput parametersarethesame. Answer: publicbooleancontainsPair(inta,intb,intc){ return(a==b||a==c||b==c); } 9)WriteamethodcalledthreeOfAKindthattakesinthreeintegerparametersandreturnstrueifallthreeofthemarethe same,falseotherwise. Answer: publicbooleanthreeOfAKind(inta,intb,intc){ return(a==b&&b==c); } 10)WriteamethodcalledrandomAveragethatgenerates100randomintegersintherange1to100(inclusive)and returnstheiraverage.YoumayassumethattheclasshasastaticRandomobjectcalledgeneratoralreadydeclaredand instantiated. 9 AddisonWesley2007

JavaFoundations:IntroductiontoProgramDesign&DataStructures JohnLewis,PeterJ.DePasquale,JosephChase TestBank:Chapter5

Answer: publicdoublerandomAverage(){ intsum=0; for(inti=0;i<100;i++) sum+=generator.nextInt(100)+1; return(double)sum/100.0; } 11)Explainwhyastaticmethodcannotrefertoaninstancevariable. Answer:Staticmethodsmaybecalledwithoutinstantiatinganobject.Therefore,aninstancevariablemaynot haveanassignedvaluewhenastaticmethodiscalled,soastaticmethodcannotreferenceit. 12)Writeamethodthatprintsyourname,age,andmajor.Themethodshouldacceptnoparametersandreturnnovalue. Answer: publicvoidmyInfo(){ System.out.println(Name:\tJohnSmith); System.out.println(Age:\t30); System.out.println(Major:\tBasketWeaving); } 13)Explainwhymethodoverloadingisuseful. Answer:Methodoverloadingisusefulbecauseitallowsmultiplemethodstohavethesamenameaslongasthey havedifferentparametertypes.Thisallowsformoreflexibilityinchoosingidentifiersformethods,sincethealternative wouldrequiretheprogrammertohavedifferentmethodidentifiersforeverymethodthattookinadifferenttypeof parameter. 14)Considerthefollowingmethod. publicvoidchangeValues(inti,Cardc){ i=15; c.setSuit(Clubs); } Nowconsiderthefollowingsnippetofcodethatcallsthemethoddefinedabove. intnum=12; CardfiveOfSpades=newCard(5,Spades); System.out.println(Beforemethodcall:); System.out.println(num); System.out.println(fiveOfSpades.getSuit()); 10 AddisonWesley2007

JavaFoundations:IntroductiontoProgramDesign&DataStructures JohnLewis,PeterJ.DePasquale,JosephChase TestBank:Chapter5

changeValues(num,fiveOfSpades); System.out.println(Aftermethodcall:); System.out.println(num); System.out.println(fiveOfSpades); Whatistheoutputofthiscode? Answer: Beforemethodcall: 12 Spades Aftermethodcall: 12 Clubs 15)Writeamethodcalledsquarethattakesinanintegervalueandreturnstheintegersquared.Yourmethodshoulduse theMath.pow()method. Answer: publicintsquare(inta){ returnMath.pow(a,2); }

11 AddisonWesley2007

JavaFoundations:IntroductiontoProgramDesign&DataStructures JohnLewis,PeterJ.DePasquale,JosephChase TestBank:Chapter8

Chapter1:Introduction MultipleChoiceQuestions:
1)Theprocessofinheritanceshouldestablisha(n)___________________relationship. a)isa b)hasa c)static d)nota e)noneoftheabove Answer:a Explanation:Inheritanceshouldestablishanisarelationship.Thereforeanyobjectsthatareofatypelowerinthe inheritancehierarchyarealsoofatypehigherintheinheritancehierarchy. 2)Theoriginalclassthatisusedtoderiveanewclassusinginheritanceiscalled____________________. a)asuperclass b)aparentclass c)abaseclass d)alloftheabove e)neithera,b,norc Answer:d Explanation:Theoriginalclasscanbecalledasuperclass,aparentclassand/orabaseclass. 3)Thederivedclasscreatedusinginheritaceiscalled______________________. a)achildclass b)asuperclass c)aparentclass d)alloftheabove e)neithera,b,norc Answer:a Explanation:Aderivedclassiscalledachildclass.Thesuperclassandtheparentclassreferstotheoriginalclass usedtoderivethechildclass. 4)Inorderforderivedclassedtohaveaccesstoencapsulateddatamembersandmethodsofsuperclasses,thedatamembers andmethodsshouldbedeclaredusingthe____________________modifier. a)private b)public c)protected d)final e)static 1 AddisonWesley2007

JavaFoundations:IntroductiontoProgramDesign&DataStructures JohnLewis,PeterJ.DePasquale,JosephChase TestBank:Chapter8

Answer:c Explanation:Datamembersandmethodsdeclaredusingtheprotectedmodifiercanbeaccessedbysubclassesin aninheritancehierarchy,butarestillencapsulatedfromclassesandmethodsoutsideofthehierarchy. 5)Thespecialreference_________________isusedtorefertotheparentclassinachildclass. a)this b)super c)null d)parent e)noneoftheabove Answer:b Explanation:Thesuperreferencereferstotheparentclassinaderivedclass. 6)Whenavariableisdeclaredinasubclasshasthesamenameasavariabledeclaredinasuperclass,itiscalleda _______________variable. a)final b)shadow c)static d)dead e)thisisnotallowedinJava Answer:b Explanation:Ashadowvariableisavariableinasubclasswiththesamenameasavariableinthesuperclass. 7)A_______________________classrepresentsagenericconceptinaclasshierarchy. a)super b)abstract c)interface d)shadow e)generic Answer:b Explanation:Anabstractclassrepresentsagenericentitythatisnotcompletelydefined.Anabstractclasscannot beinstantiated.Itcontainsoneormoreabstractmethods,whicharemethodsthatshouldbeoverriddenbysubclasses. 8)Aclassdeclaredasfinal_________________________________. a)cannotbechanged. b)cannothavesubclasses. c)cannothavesuperclasses. d)hasseveralabstractmethods. e)cannotbeusedinaprogram.

2 AddisonWesley2007

JavaFoundations:IntroductiontoProgramDesign&DataStructures JohnLewis,PeterJ.DePasquale,JosephChase TestBank:Chapter8 Answer:b Explanation:Thefinalmodifierrestrictsinheritance.Inparticular,aclassdeclaredasfinalcannothave subclasses. 9)Whichofthefollowingkeywordsindicatesanewclassisbeingderivedfromanexistingclass? a)super b)final c)extends d)inherits e)expands Answer:c Explanation:Thekeywordextendsindicatesthatanewclassisbeingderivedfromanexistingclass. 10)Toinvokeaparentsconstructorinasubclass,weusethe______________method. a)abstract b)construct c)parent d)super e)extends Answer:d Explanation:Thesupermethodisusedtoinvokeaparentsconstructorfromasubclass. 11)Ifasubclassesconstructordoesnotmakeanexplicitcalltoasuperclass'sconstructor,______________________. a)aruntimeerrorwillresult. b)acompiletimeerrorwillresult. c)theconstructorwillbecalledanyway. d)theclasswillbeimplicitlydeclaredasabstract. e)noneoftheabove Answer:c Explanation:Thechild'sconstructorwillimplicitlycallthesuperclass'sconstructorifitisnotdoneexplicitly.This willensurethattheclassisproperlyinitialized. 12)AllJavaclassesaresubclassesofthe___________________class. a)String b)java.lang c)Java d)Class e)Object Answer:e Explanation:AllclassesaresubclassesofJava'sObjectclass,whetherexplicitlyspecifiedornot. 3 AddisonWesley2007

JavaFoundations:IntroductiontoProgramDesign&DataStructures JohnLewis,PeterJ.DePasquale,JosephChase TestBank:Chapter8

13)Whendesigningaclasshierarchy,itisimportantthatcommonfeaturesbe________________________. a)higherintheclasshierarchy. b)lowerintheclasshierarchy. c)nearthemiddleoftheclasshierarchy. d)inabstractclasses. e)intheObjectclass. Answer:a Explanation:Commonfeaturesshouldbeincludedclosertothetopoftheclasshierarchy.Doingthismakesthem availabletomoreclasseslowerinthehierarchy. 14)WhichofthefollowingmethodsareincludedineveryclasscreatedinJavabyinheritance? a)next b)toString c)compareTo d)charAt e)noneoftheabove Answer:b Explanation:ThetoStringmethodisdefinedintheObjectclass,andisthereforeincludedineveryJavaclass viainheritance. 15)Oftheclassesbelow,theonethatismostlikelytobedeclaredabstractis_________________. a)Bat b)Squirrel c)Animal d)Iguana e)Parrot Answer:c Explanation:TheAnimalclassismostlikelytobeabstractsinceitisthemostgeneric.

4 AddisonWesley2007

JavaFoundations:IntroductiontoProgramDesign&DataStructures JohnLewis,PeterJ.DePasquale,JosephChase TestBank:Chapter8

True/FalseQuestions:
1)Methodsandvariablesdeclaredasprivateinaparentclasscannotbeaccessedinachildclass. Answer:True Explanation:Inorderforachildclasstohaveaccesstotheprivatedataandmethodsofaparentclass,theyshould bedeclaredusingtheprotectedmodifier,whichstillenforcesencapsulation,butallowsforflexibilityinaninheritance hierarchy. 2)Onceamethodisoverriddeninasubclass,theoriginalversioncanneverbereferencedfromwithinthesubclass. Answer:False Explanation:Theoriginalversionofthemethodcanbeaccessedusingthesuperreference. 3)Javasupportsmultipleinheritance. Answer:False Explanation:Javadoesnotsupporttruemultipleinheritance,butitispossibletogetsomeofthefeaturesof multipleinheritanceusinginterfaces. 4)InJavasubclasscanonlyextendoneparentclass. Answer:True Explanation:Allowingasubclasstoextendmultipleparentclassesleadstomultipleinheritance,whichisnot supportedinJava. 5)Achildclassisallowedtodefineamethodwiththesamenameandparameterlistasamethodintheparentclass. Answer:True Explanation:Asubclassisallowedtooverridemethodsthatareintheparentclass. 6)Achildclassisallowedtodeclareavariablewiththesamenameasonethatiscontainedintheparentclass. Answer:True Explanation:Thisisknownasvariableshadowingandcanleadtoconfusion.Itis,however,permittedinJava. 7)Anabstractclassmustcontainabstractmethods. Answer:False Explanation:Aclassdeclaredasabstractmayormaynotcontainabstractmethods. 8)Itmakessensetodeclaremostabstractmethodsasfinal. Answer:True Explanation:Sinceanabstractclasscannotbeinstantiated,itmakesnosensetodeclareitasfinal.Itisusually expectedthatanabstractclasswillbeextended. 9)Itispossibletoderiveaclassfromanabstractclasswithoutoverridingalloftheparentsabstractmethods. Answer:True Explanation:Thechildclassmustalsobedeclaredasabstractinthiscase. 10)Inheritanceshouldnotbeconsideredinthesoftwaredesignprocess. Answer:False Explanation:Inheritanceshouldbecarefullyconsideredinthesoftwaredesignprocess.Softwaresystemsdesigned carefullyusinginheritancecanbemoreflexiblethansoftwaredesignedwithoutconsideringinheritance.

5 AddisonWesley2007

JavaFoundations:IntroductiontoProgramDesign&DataStructures JohnLewis,PeterJ.DePasquale,JosephChase TestBank:Chapter8

ShortAnswerQuestions:
1)Explainwhyinheritanceisuseful. Answer:Inheritanceisusefulbecauseitallowsforcodereuse.Thismeansthatifwehavemultiplesoftware entitiesthathavecommonfeatures,thecodeforthecommonfeaturescanbewrittenonceinasuperclass.Theclassesthat includethesefeaturescanthenbewrittenviainheritance,andthiscommoncodedoesnothavetoberewritten. 2)Compareandcontrasttheprivatevisibilitymodifiertotheprotectedvisibilitymodifier.Whyisthe protectedvisibilitymodifierabetterchoiceinaninheritancehierarchy? Answer:Theprivatemodifierandtheprotectedmodifierbothenforcetheencapsulationofinstance variablesandmethodsinaclass.Thismeansthatunrelatedclassesarenotabletodirectlyaccessthevariablesandthe methods.Theprotectedmodifier,however,doesallowfortheinstancevariablesandthemethodstobeaccessedby subclassesoftheoriginalclass.Thismakestheprotectedmodifierabetterchoiceforuseinaninheritancehierarchy, becauseitisoftenusefulforsubclassestohaveaccesstoasuperclass'sinstancevariablesandmethods. 3)SupposewecreateasubclassfromaclassthathasamethodcalledsomeMethod.IfweoverridesomeMethodinthe subclass,isitpossibletoaccessthesuperclass'sversionofsomeMethod?Ifso,how? Answer:Yes,itispossibletoaccesstheoriginalversionofthemethod.Todoso,wequalifythecalltothemethod withthesuperreference.Inotherwords,toaccesstheoriginalversionofthemethodwecallsuper.someMethod(). 4)Canaclassbeaparentofmorethanonesubclass?Canaclassbeachildofmorethanoneparent?Explain. Answer:Aclasscanbetheparentofmorethanonesubclassinaninheritancehierarchy.Classesthathavethe sameparentclassareoftencalledsiblings.InJava,aclasscannotbethechildofmorethanoneparentsinceJavadoesnot supportmultipleinheritance. 5)ExplaintherelevanceoftheObjectclasstotheJavaprogramminglanguage. Answer:EveryclassinJavaisasubclassoftheObjectclass.Thisoccurswhetheraclassdefinitionexplicitly extendstheObjectclassornot.Therefore,everyclassinJavahasacommonsetofmethodsthataredefinedinthe Objectclass.TheseincludethetoStringmethodandtheequalsmethod. 6)Whatisanabstractclass,andwhymightitbeusefulinaninheritancehierarchy? Answer:Anabstractclassisaclassrepresentsapartiallydefinedconceptinaninheritancehierarchy.Abstract methodscannotbeinstantiated,buttheycanbeextended.Theyareoftenusefulbecauseseveralclassesmayinclude commonfunctionalitybutmaylackafullydefinedparentconcept.Abstractclassesallowaprogrammertoimplementthe partiallydefinedparentconceptasanabstractclasswhichwillincludethecommonfunctionalityofthechildclasses.An exampleofanabstractconceptinaninheritancehierarchymightbeaVehicle.SubclasseslikeCar,Boatand Airplanearemorefullydefined,buttheysharecommonstatesandbehaviors. 7)Explainhowasubclasscancanaccessitsparentclassesprivateinstancevariablesandmethods. Answer:Asubclasscanaccessprivateinstancevariablesandmethodsofitsparentclass,butonlyindirectly. Theremustbepublicmethodsthataccesstheprivatedataandmethodsdirectly.Thesepublicmethodscanthenbecalledby 6 AddisonWesley2007

JavaFoundations:IntroductiontoProgramDesign&DataStructures JohnLewis,PeterJ.DePasquale,JosephChase TestBank:Chapter8 thesubclass,whichgivesindirectaccesstotheprivatevariablesandmethodsoftheparentclass. 8)AprogrammertriestocreateasubclassofStringcalledMyString.Whentheprogrammercompileshernewclass, thecompilerproducesthefollowingmessage: MyString.java:1:cannotinheritfromfinaljava.lang.String publicclassMyStringextendsString{ ^ 1error Explainthecauseofthiserror. Answer:TheStringclasshasbeendeclaredwiththefinalmodifier,whichrestrictsanyotherclassesfrom extendingit. 9)DrawahierarchyofAnimals.Thehierarchyshouldincludethefollowingentities:Animal,Reptile,Mammal,Bear, Human,Iguana,andDolphin. Answer: Animal / \ ReptileMammal //|\ IguanaBearHumanDolphin 10)Consideransoftwaresystemthatwillimplementthefollowingclasses:Student,Professor,StaffMember, ContractWorker.Listsomecommonattributesoftheseclasses.Whatwouldbeagoodabstractclassfromwhich theseclassesmaybeextendedviainheritance? Answer:SomecommonattributeswouldbesocialSecurityNumber,age,andaddress.Agoodabstract classfromwhichtheseclassescouldbeextendedisPerson. 11)Explainwhatitmeansforachildclasstooverrideaparentclass.Whymightthisbeuseful? Answer:Achildclassoverridesamethodthatisinheritedfromaparentclassbyredefiningitinthesubclass.This isusefulbecauseasubclassmayhaveaslightlydifferentbehaviorthanthesuperclass,butthebehaviorstillhasthesame name.Overridingmethodsallowsforthisflexibility. 12)DrawahierarchyofpeopleataUniversity. Answer: UniversityPerson /|\ FacultyStaffStudent /|/\ ProfessorsInstructorsGraduateUndergraduate

7 AddisonWesley2007

JavaFoundations:IntroductiontoProgramDesign&DataStructures JohnLewis,PeterJ.DePasquale,JosephChase TestBank:Chapter8

13)DescribethebehaviorofthetoStringmethodandtheequalsmethodoftheObjectclass. Answer:ThetoStringmethodreturnsaStringrepresentationofanobject.Theequalsmethodreturnstrueif theobjectisanaliasoftheobjectsentinasaparameter. 14)Whatdoesitmeanforaclasstobedeclaredasfinal?Whatdoesitmeanforamethodtobedeclaredasfinal? Answer:Amethoddeclaredasfinalcannotbeoverriddenbyanysubclass.Aclassdeclaredasfinalcannot beextendedviainheritance. 15)Whatisashadowvariable? Answer:Ashadowvariableisavariablethatisdeclaredinasubclassthathasthesamenameasavariable declaredintheclass'sparentclass.

8 AddisonWesley2007

JavaFoundations:IntroductiontoProgramDesign&DataStructures JohnLewis,PeterJ.DePasquale,JosephChase TestBank:Chapter9

Chapter1:Introduction MultipleChoiceQuestions:
1)Apolymorphicreferenceisonethatcanreferto_______________type(s)ofobject(s). a)exactlyone b)zero c)multiple d)abstract e)static Answer:c Explanation:Apolymorphicreferencecanpointtomultipletypesofobjectsatdifferentpointsintime. 2)Thecommitmenttoexecutecertaincodetocarryoutamethodinvocationisreferredtoas_________________. a)execution b)binding c)polymorphism d)inheritance e)noneoftheabove Answer:b Explanation:Bindingreferstothecommitmenttoexecutecertaincodetocarryoutamethodinvocation. 3)InJava,polymorphicmethodbindingoccurs____________________. a)atruntime b)atcompiletime c)never d)whenaprogrammerwritesthecode e)duringthetestingphaseofsoftwaredevelopment Answer:a Explanation:polymorphicmethodbindingoccursatruntime. 4)Latebindingis_______________than_______________. a)moreefficient,compiletimebinding b)lessefficient,compiletimebinding c)moreefficient,runtimebinding d)lessefficient,runtimebinding e) Answer:b Explanation:Latebindingislessefficientthancompiletimebindingduetotheoverheadassociatedwith 1 AddisonWesley2007

JavaFoundations:IntroductiontoProgramDesign&DataStructures JohnLewis,PeterJ.DePasquale,JosephChase TestBank:Chapter9 determiningthecodethatshouldbeexecutedatruntime. 5)SupposethatHorseisasubclassofAnimal,andneitherclassisabstract.Whichofthefollowingisaninvalid declarationandinitialization? a)Horseh=newHorse(); b)Horseh=newAnimal(); c)Animala=newAnimal(); d)Animala=newHorse(); e)alloftheabovearevalid Answer:b Explanation:SinceHorseisasubclassofAnimal,choicebwouldrequireanexplicitclass. 6)InJava,a(n)___________________isacollectionofconstantsandabstractmethods. a)polymorphicreference b)abstractclass c)implementation d)interface e)iterator Answer:d Explanation:Aninterfaceisacollectionofconstantsandabstractmethods. 7)InJava,polymorphicreferencescanbecreatedthroughtheuseof__________________and________________. a)inheritance,interfaces b)inheritance,abstractclasses c)interfaces,abstractclasses d)interfaces,iterators e)noneoftheabove Answer:a Explanation:InJava,polymorphicreferencescanbecreatedthroughtheuseofinheritanceandinterfaces. 8)LetDogbeasubclassofAnimal,andsupposeAnimalhasamethodcalledspeak()thatisoverriddenintheDogclass. Considerthefollowingcode. Animalspot=newDog(); spot.speak(); Whichofthefollowingistrue? a)Thiscodewillresultinacompiletimeerror. b)Thiscodewillresultinaruntimeerror. c)ThespeakmethoddefinedintheAnimalclasswillbecalled. d)ThespeakmethoddefinedintheDogclasswillbecalled. 2 AddisonWesley2007

JavaFoundations:IntroductiontoProgramDesign&DataStructures JohnLewis,PeterJ.DePasquale,JosephChase TestBank:Chapter9 e)Thespeakmethodwillnotbecalledatall. Answer:d Explanation:ThespeakmethoddefinedintheDogclasswillbecalledinthiscase.Atruntime,theJavavirtual machinedeterminesthatspotispointingtoanobjectoftypeDogandbindsthemethodtothemethodsdefinedintheDog class. 9)TheComparableinterfacecontainswhichofthefollowingmethods? a)isGreaterThan b)isLessThan c)equals d)compareTo e)alloftheabove Answer:d Explanation:TheComparableinterfacecontainsexactlyonemethodcompareTo. 10)LetObjectabelargerthanObjectb.Whatwillthefollowingmethodcallreturn? a.compareTo(b) a)itwillreturn0 b)itwillreturnanumbergreaterthan0 c)itwillreturnanumberlessthan0 d)itwillreturntrue e)itwillreturnfalse Answer:b Explanation:ThecompareTomethodreturnsaninteger.IfObjectaisbiggerthanObjectb,itwillreturn anumbergreaterthan0.IfObjectaislessthanObjectb,itwillreturnanumberlessthan0.Iftheyareequalit return0. 11)WhichofthefollowingmethodsareincludedwithanyobjectthatimplementstheIteratorinterface? a)next b)hasNext c)toString d)alloftheabove e)aandb Answer:d Explanation:TheIteratorinterfacespecifiesthatallobjectsthatimplementitmusthavethehasNextandnext methods.SinceallobjectsinJavaareasubclassoftheObjectclass,itwillalsoincludethetoStringmethod. 12)Inordertocreateaclassthatimplementsaninterface,the__________________keywordisused.

3 AddisonWesley2007

JavaFoundations:IntroductiontoProgramDesign&DataStructures JohnLewis,PeterJ.DePasquale,JosephChase TestBank:Chapter9 a)extends b)interfaces c)implements d)finalizes e)abstracts Answer:c Explanation:Aclassthatimplementsaninterfaceusestheimplementskeywordtodeclaretheclass. 13)Considerthefollowinglineofcode. Comparables=newString(); Whichofthefollowingstatementsistrueaboutthisline? a)Itwillresultinacompiletimeerror. b)Itwillresultinaruntimeerror. c)ItwillcreateaStringobjectpointedtobyaComparablereference. d)AlthoughitisperfectlyvalidJava,itshouldbeavoidedduetoconfusion. e)noneoftheabovearetrue Answer:c Explanation:ThisisavalidJavastatementandwillresultinnoerrors,sincetheStringclassimplementsthe Comparableinterface. 14)SupposeAnimalisaninterfacethatspecifiesasinglemethodspeak.NowsupposetheDogclassimplementsthe Animalinterface.Inadditiontothespeakmethod,theDogclassalsohasamethodcalledwagTail.Nowconsiderthe followingcode. Animala=newDog(); a.wagTail(); Whichofthefollowingistrueaboutthiscode? a)Itwillresultinacompiletimeerror. b)Itwillresultinaruntimeerror. c)ItwillcallthespeakmethoddefinedintheAnimalinterface. d)ItwillcallthewagTailmethoddefinedintheDogclass. e)noneoftheabovearetrue. Answer:a Explanation:ThiscodewillresultinacompiletimeerrorsincetheAnimalinterfacedoesnotspecifya wagTailmethod.ThiscompiletimeerrorcanbeavoidedbyexplicitlycastingaasaDogwhencallingthewagTail method. 15)WhichGUIconceptsusepolymorphismtoestablishtheirrelationship? a)alisteneranditsassociatedcomponent 4 AddisonWesley2007

JavaFoundations:IntroductiontoProgramDesign&DataStructures JohnLewis,PeterJ.DePasquale,JosephChase TestBank:Chapter9 b)aradiobuttonanditsdefaultselection c)abuttonanditslabel d)aslideranditstickmarks e)noneoftheabove Answer:a Explanation:Polymorphismisusedtoestablishtherelationshipbetweenalisteneranditsassociatedcomponent.

5 AddisonWesley2007

JavaFoundations:IntroductiontoProgramDesign&DataStructures JohnLewis,PeterJ.DePasquale,JosephChase TestBank:Chapter9

True/FalseQuestions:
1)Considerareferencedeclaredinthefollowingmanner. Animala; ThisreferencemayonlypointtoanobjectthatcreatedbyinstantiatingtheAnimalclass. Answer:False Explanation:ThisreferencemaypointtoanobjectofanytypethatiscompatiblewithAnimal.Inparticular,it maypointtoanyobjectthatisaninstanceofaclassthatisasubclassofAnimal. 2)LetAnimalbeaninterface.ThenitispossibletocreateanobjectbyinstantiatingtheAnimalinterface. Answer:False Explanation:Aninterfacecannotbeinstantiated. 3)ThecompareTomethodoftheComparableinterfacereturnsabooleanvalue. Answer:False Explanation:ThecompareTomethodreturnsaninteger. 4)ThenextmethodoftheIteratorinterfacereturnsareferencetothenextelementinacollectionandremovesit. Answer:False Explanation:Thenextmethodonlyreturnsareferencetothenextelementinacollection;itdoesnotremoveit. 5)Aparametertoamethodcanbepolymorphic. Answer:True Explanation:Amethodcanacceptapolymorphicreference;thisgivesthemethodmoreflexibilitythanitwould otherwisehave. 6)Aninterfacecannotdeclareanyinstancevariables. Answer:True Explanation:Aninterfacemayonlydeclareconstants. 7)Establishingtherelationshipbetweenalistenerandthecomponentitlistenstoisaccomplishedusingpolymorphism. Answer: Explanation: 8)Ifaclassimplementsaninterface,itcannotextendanotherclass. Answer:False Explanation:Aclassmayimplementaninterfaceandextendanotherclass. 9)Asingleclassmayimplementmultipleinterfaces. Answer:True Explanation:Aclassmayimplementmultipleinterfaces,whichgivesJavamanyofthegoodfeaturesofmultiple inheritance. 10)Aninterfacenamemaybeusedasareferencetype. Answer:True 6 AddisonWesley2007

JavaFoundations:IntroductiontoProgramDesign&DataStructures JohnLewis,PeterJ.DePasquale,JosephChase TestBank:Chapter9 Explanation:Aninterfacenamemaybeusedareferencetypeinthesamewaythataclassnamemaybeusedasa referencetype.Likeanabstractclass,aninterfacecannotbeinstantiated,however.

7 AddisonWesley2007

JavaFoundations:IntroductiontoProgramDesign&DataStructures JohnLewis,PeterJ.DePasquale,JosephChase TestBank:Chapter9

ShortAnswerQuestions:
1)Whatispolymorphism? Answer:Apolymorphicreferenceisasingletypeofreferencethatcanpointtodifferenttypesofobjectsat differenttimes.Polymorphismreferstothefactthatthemethodcallsonpolymorphicreferencesareselectedbytheobject type,notthereferencetype.Thisisoftenreferredtoaslatebinding. 2)HowdoesinheritancerelatetopolymorphisminJava? Answer:Inheritanceistheprocessbywhichpolymorphicreferencesarecreated.Areferencetoatypehigherin aninheritancehierarchycanalwayspointtoanobjectofatypelowerinaninheritancehierarchyduetotheisarelationship. 3)ConsideraclasshierarchythatincludesaclasscalledVehicle,withsubclassescalledCarandAirplane.The VehicleclasshasamethodcalledgetMaxSpeed,whichisoverriddenintheCarclass.ThegetMaxSpeedofthe Vehicleclassreturns760mph,whilethegetMaxSpeedmethodoftheCarclassisoverriddentoreturn150mph. Whatistheoutputofthefollowingsnippetofcode?Explainyouranswer. Vehiclev=newCar(); System.out.println(v.getMaxSpeed()+mph); Answer:Theoutputofthiscodewillbe150mph.EventhoughthereferenceistotheVehicleclass,the getMaxSpeedmethodisboundtothedefinitionintheCarclass,sincetheobjectisacar.Thisisduetothepolymorphic natureofthereference. 4)Considerthefollowinginheritancehierarchythatisusedinavideogame. Character /\ FriendVillain /\/\ WiseManShopKeeperDragonSkeleton || FlyingDragonEliteSkeleton Whichofthefollowingdeclarationsandinitializationswillnotcauseacompilererror? Characterc=newFlyingDragon(); FlyingDragonf=newCharacter(); Dragond=newVillain(); Villainv=newSkeleton(); Dragond=newShopKeeper(); Answer:Thefollowingarevalidforthisinheritancehierarchybecauseoftheisarelationship. Characterc=newFlyingDragon(); 8 AddisonWesley2007

JavaFoundations:IntroductiontoProgramDesign&DataStructures JohnLewis,PeterJ.DePasquale,JosephChase TestBank:Chapter9 Villainv=newSkeleton(); 5)Whatisaninterface? Answer:Aninterfaceisacollectionofabstractmethodsandconstants. 6)Arethereanydifferencesbetweenextendingaclassandimplementinganinterface? Answer:Yes.First,extendingaclassusestheextendskeyword,whileimplementinganinterfaceusesthe implementskeyword.Moreimportantly,aclasscanimplementmultipleinterfaces,whileitcanonlyextendasingleclass. 7)DescribethecompareTomethodthecircumstancesunderwhichitreturnsdifferentvalues. Answer:ThecompareTomethodisspecifiedbytheComparableinterface.Itplacesanorderingonobjects. ConsiderthefollowingcalltocompareTo: intresult=obj1.compareTo(obj2); Inthiscaseresultwillbepositiveifobj1islargerthanobj2inthesenseoftheordering.Itwillbe0ifobj1andobj2 arethesame,anditwillbenegativeifobj2islargerthanobj1. 8)Howdointerfacesrelatetomultipleinheritance? Answer:InJava,interfacesgivemanyofthefeaturesofmultipleinheritancewithoutmanyoftheproblems.In particular,aclasscanimplementmultipleinterfaces,whichallowsobjectstobeofseveraldifferenttypes.Sinceallthe methodsareabstractintheinterfaces,however,thereisnoambiguitywhenmethodsappearindifferentinterfaceswiththe samename. 9)Canreferencestointerfacetypesbepolymorphic?Explain. Answer:Yestheycan.Hierarchiescanbecreatedbyimplementinginterfacesinthesamewaythattheycanbe createdbyextendingclasses.Polymorphismisthesameineithercase. 10)WriteaninterfaceforaCDplayer.Itshouldhavethestandardoperations(i.e.play,stop,etc)thatusualCDplayers have. Answer: publicinterfaceCDPlayer{ publicvoidplay(); publicvoidstop(); publicvoidnextTrack(); publicvoidpreviousTrack();

9 AddisonWesley2007

JavaFoundations:IntroductiontoProgramDesign&DataStructures JohnLewis,PeterJ.DePasquale,JosephChase TestBank:Chapter9 publicvoidseekForward(); publicvoidseekBackwards(); } 11)GiveanexampleofaclassthatimplementstheComparableinterface,andexplainhowtheimplementationofthe compareTomethoddeterminesitsreturnvalue. Answer:TheStringclassimplementstheComparableinterface.Thecomparisonisbasedonthe lexicographicorderingofStringobjectsdefinedbytheUnicodecharacterset. 12)DescribetheIteratorinterface. Answer:TheIteratorinterfaceprovidesamethodofmovingthroughacollectionofobjectsoneatatime.It includesthenextmethodwhichreturnsthenextelementinthecollectionandthehasNextmethodwhichreturnstrue onlyifthereisanotherelementinthecollection. 13)GiveanexampleofaclassthatimplementstheIteratorinterface. Answer:TheScannerclassimplementstheIteratorinterface. 14)SupposeyouareimplementingthecomparableinterfaceinaclassrepresentingaPerson,wheretheorderingisbased ontheageoftheperson.WriteacompareTomethodforthisclass.Youmayassumethatthereisaninstancevariablecalled ageandamethodcalledgetAge. Answer: publicintcompareTo(Objecto){ Personp=(Person)o; returnthis.getAge()p.getAge(); } 15)Whycan'taninterfacebeinstantiated? Answer:Aninterfacecannotbeinstantiatedbecause,similartoanabstractclass,itonlycontainsabstractmethods.

10 AddisonWesley2007

Das könnte Ihnen auch gefallen