《java教材课件jhtp8_ch08》由会员分享,可在线阅读,更多相关《java教材课件jhtp8_ch08(136页珍藏版)》请在金锄头文库上搜索。
1、Java How to Program, 8/e123Deeperlookatbuildingclasses,controllingaccesstomembersofaclassandcreatingconstructors.Compositionacapabilitythatallowsaclasstohavereferencestoobjectsofotherclassesasmembers.Moredetailsonenumtypes.Discussstaticclassmembersandfinalinstancevariablesindetail.Showhowtoorganizec
2、lassesinpackagestohelpmanagelargeapplicationsandpromotereuse.4ClassTime1representsthetimeofday.privateintinstancevariableshour,minuteandsecondrepresentthetimeinuniversal-timeformat(24-hourclockformatinwhichhoursareintherange023).publicmethodssetTime,toUniversalStringandtoString. Clledthepublicservic
3、esorthepublicinterfacethattheclassprovidestoitsclients.56789ClassTime1doesnotdeclareaconstructor,sotheclasshasadefaultconstructorthatissuppliedbythecompiler.Eachinstancevariableimplicitlyreceivesthedefaultvalue0foranint.Instancevariablesalsocanbeinitializedwhentheyaredeclaredintheclassbody,usingthes
4、ameinitializationsyntaxaswithalocalvariable.10ATime1objectalwayscontainsconsistent data Theobjectsdatavaluesarealwayskeptinrange,evenifthevaluesprovidedasargumentstomethodsetTimewereincorrect. Inthisexample,zeroisaconsistentvalueforhour,minuteandsecond.hour,minuteandsecondareallsettozerobydefault;th
5、us,aTime1objectcontainsconsistentdatafromthemomentitiscreated.11Importanttodistinguishbetweenacorrect value andaconsistent value. Aconsistentvalueforminutemustbeintherange0to59. Acorrectvalueforminuteinaparticularapplicationwouldbetheactualminuteatthattimeofday. Settingthetimeonawatch. Iftheactualti
6、meis17minutesafterthehourandyouaccidentlysetthewatchto19minutesafter,the19isaconsistent value(0to59)butnota correct value. Ifyousetthewatchto17minutesafterthehour,then17isacorrectvalueandacorrectvalueisalways aconsistentvalue.12Forinconsistentvalues,wecouldsimplyleavetheobjectinitscurrentstate,witho
7、utchangingtheinstancevariable. TimeobjectsbegininaconsistentstateandsetTimemethodrejectsanyinconsistentvalues Objectalwaysguaranteed tobeinaconsistentstate. Oftenthatstatewouldbetheobjectslastcorrectstate,whichsomedesignersfeelissuperiortosettingtheinstancevariablestozero.13Potentialproblems Approac
8、hesdiscussedsofardonotinformtheclientcodeofinconsistentvalues. setTimecouldreturnavaluesuchastrueifallthevaluesareconsistentandfalseifanyofthevaluesareinconsistent. Thecallerwouldcheckthereturnvalue,andifitwerefalse,wouldattempttosetthetimeagain. Problem:SomeJavatechnologies(suchasJavaBeans)requiret
9、hattheset methodsreturnvoid. InChapter11,ExceptionHandling,youlllearntechniquesthatenableyourmethodstoindicatewheninconsistentvaluesarereceived.14Theinstancevariableshour,minuteandsecondareeachdeclaredprivate.Theactualdatarepresentationusedwithintheclassisofnoconcerntotheclasssclients.ReasonableforT
10、ime1torepresentthetimeinternallyasthenumberofsec-ondssincemidnightorthenumberofminutesandsecondssincemidnight.Clientscouldusethesamepublicmethodsandgetthesameresultswithoutbeingawareofthis.151617Accessmodifierspublicandprivatecontrolaccesstoaclasssvariablesandmethods. Chapter9introducesaccessmodifie
11、rprotected.publicmethodspresenttotheclasssclientsaviewoftheservicestheclassprovides(theclassspublicinterface).Clientsneednotbeconcernedwithhowtheclassaccomplishesitstasks. Forthisreason,theclasssprivatevariablesandprivatemethods(i.e.,itsimplementationdetails)arenotaccessibletoitsclients.privateclass
12、membersarenotaccessibleoutsidetheclass.18192021Everyobjectcanaccessareferencetoitselfwithkeywordthis.Whenanon-staticmethodiscalledforaparticularobject,themethodsbodyimplicitlyuseskeywordthistorefertotheobjectsinstancevariablesandothermethods. Enablestheclassscodetoknowwhichobjectshouldbemanipulated.
13、 Canalsousekeywordthisexplicitlyinanon-staticmethodsbody.Canusethethisreferenceimplicitlyandexplicitly.22Whenyoucompilea.javafilecontainingmorethanoneclass,thecompilerproducesaseparateclassfilewiththe.classextensionforeverycompiledclass.Whenonesource-code(.java)filecontainsmultipleclassdeclarations,
14、thecompilerplacesbothclassfilesforthoseclassesinthesamedirectory.Asource-codefilecancontainonlyonepublicclassotherwise,acompilationerroroccurs.Non-publicclassescanbeusedonlybyotherclassesinthesamepackage.23242526SimpleTimedeclaresthreeprivateinstancevariableshour,minuteandsecond.Ifparameternamesfort
15、heconstructorthatareidenticaltotheclasssinstance-variablenames. Wedontrecommendthispractice Useitheretoshadow(hide)thecorrespondinginstance Illustratesacaseinwhichexplicituseofthethisreferenceisrequired.Ifamethodcontainsalocalvariablewiththesamenameasafield,thatmethodusesthelocalvariableratherthanth
16、efield. Thelocalvariableshadows thefieldinthemethodsscope. Amethodcanusethethisreferencetorefertotheshadowedfieldexplicitly.27282930Overloadedconstructorsenableobjectsofaclasstobeinitializedindifferentways.Tooverloadconstructors,simplyprovidemultipleconstructordeclarationswithdifferentsignatures.Recallthatthecompilerdifferentiatessignaturesbythenumber ofparameters,the types oftheparametersandtheorder oftheparametertypesineachsignature.31ClassTime2(Fig.8.5)containsfiveoverloadedconstructorsthatpr