java教材课件jhtp8_ch08

上传人:清晨86****784 文档编号:213903654 上传时间:2021-11-22 格式:PPT 页数:136 大小:19.36MB
返回 下载 相关 举报
java教材课件jhtp8_ch08_第1页
第1页 / 共136页
java教材课件jhtp8_ch08_第2页
第2页 / 共136页
java教材课件jhtp8_ch08_第3页
第3页 / 共136页
java教材课件jhtp8_ch08_第4页
第4页 / 共136页
java教材课件jhtp8_ch08_第5页
第5页 / 共136页
点击查看更多>>
资源描述

《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

展开阅读全文
相关资源
正为您匹配相似的精品文档
相关搜索

最新文档


当前位置:首页 > 高等教育 > 大学课件

电脑版 |金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号