java语言程序设计 基础篇 原书第八版 课件 PPT(第十七章).ppt_第1页
java语言程序设计 基础篇 原书第八版 课件 PPT(第十七章).ppt_第2页
java语言程序设计 基础篇 原书第八版 课件 PPT(第十七章).ppt_第3页
java语言程序设计 基础篇 原书第八版 课件 PPT(第十七章).ppt_第4页
java语言程序设计 基础篇 原书第八版 课件 PPT(第十七章).ppt_第5页
免费预览已结束,剩余57页可下载查看

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1 Chapter8ObjectsandClasses 2 Motivations Afterlearningtheprecedingchapters youarecapableofsolvingmanyprogrammingproblemsusingselections loops methods andarrays However theseJavafeaturesarenotsufficientfordevelopinggraphicaluserinterfacesandlargescalesoftwaresystems Supposeyouwanttodevelopagraphicaluserinterfaceasshownbelow Howdoyouprogramit 3 Objectives Todescribeobjectsandclasses anduseclassestomodelobjects 8 2 TouseUMLgraphicalnotationstodescribeclassesandobjects 8 2 Todemonstratedefiningclassesandcreatingobjects 8 3 Tocreateobjectsusingconstructors 8 4 Toaccessobjectsviaobjectreferencevariables 8 5 Todefineareferencevariableusingareferencetype 8 5 1 Toaccessanobject sdataandmethodsusingtheobjectmemberaccessoperator 8 5 2 Todefinedatafieldsofreferencetypesandassigndefaultvaluesforanobject sdatafields 8 5 3 Todistinguishbetweenobjectreferencevariablesandprimitivedatatypevariables 8 5 4 TouseclassesDate Random andJFrameintheJavalibrary 8 6 Todistinguishbetweeninstanceandstaticvariablesandmethods 8 7 Todefineprivatedatafieldswithappropriategetandsetmethods 8 8 Toencapsulatedatafieldstomakeclasseseasytomaintain 8 9 Todevelopmethodswithobjectargumentsanddifferentiatebetweenprimitive typeargumentsandobject typearguments 8 10 Tostoreandprocessobjectsinarrays 8 11 4 OOProgrammingConcepts Object orientedprogramming OOP involvesprogrammingusingobjects Anobjectrepresentsanentityintherealworldthatcanbedistinctlyidentified Forexample astudent adesk acircle abutton andevenaloancanallbeviewedasobjects Anobjecthasauniqueidentity state andbehaviors Thestateofanobjectconsistsofasetofdatafields alsoknownasproperties withtheircurrentvalues Thebehaviorofanobjectisdefinedbyasetofmethods 5 Objects Anobjecthasbothastateandbehavior Thestatedefinestheobject andthebehaviordefineswhattheobjectdoes 6 Classes Classesareconstructsthatdefineobjectsofthesametype AJavaclassusesvariablestodefinedatafieldsandmethodstodefinebehaviors Additionally aclassprovidesaspecialtypeofmethods knownasconstructors whichareinvokedtoconstructobjectsfromtheclass 7 Classes 8 UMLClassDiagram 9 Example DefiningClassesandCreatingObjects Objective Demonstratecreatingobjects accessingdata andusingmethods TestCircle1 Run 10 Example DefiningClassesandCreatingObjects Objective Demonstratecreatingobjects accessingdata andusingmethods TestTV Run TV 11 Constructors Circle Circle doublenewRadius radius newRadius Constructorsareaspecialkindofmethodsthatareinvokedtoconstructobjects 12 Constructors cont Aconstructorwithnoparametersisreferredtoasano argconstructor Constructorsmusthavethesamenameastheclassitself Constructorsdonothaveareturntype notevenvoid Constructorsareinvokedusingthenewoperatorwhenanobjectiscreated Constructorsplaytheroleofinitializingobjects 13 CreatingObjectsUsingConstructors newClassName Example newCircle newCircle 5 0 14 DefaultConstructor Aclassmaybedeclaredwithoutconstructors Inthiscase ano argconstructorwithanemptybodyisimplicitlydeclaredintheclass Thisconstructor calledadefaultconstructor isprovidedautomaticallyonlyifnoconstructorsareexplicitlydeclaredintheclass 15 DeclaringObjectReferenceVariables Toreferenceanobject assigntheobjecttoareferencevariable Todeclareareferencevariable usethesyntax ClassNameobjectRefVar Example CirclemyCircle 16 Declaring CreatingObjectsinaSingleStep ClassNameobjectRefVar newClassName Example CirclemyCircle newCircle Createanobject Assignobjectreference 17 AccessingObjects Referencingtheobject sdata objectRefVar datae g myCircle radiusInvokingtheobject smethod objectRefVar methodName arguments e g myCircle getArea 18 TraceCode CirclemyCircle newCircle 5 0 SCircleyourCircle newCircle yourCircle radius 100 DeclaremyCircle novalue myCircle animation 19 TraceCode cont CirclemyCircle newCircle 5 0 CircleyourCircle newCircle yourCircle radius 100 novalue myCircle Createacircle animation 20 TraceCode cont CirclemyCircle newCircle 5 0 CircleyourCircle newCircle yourCircle radius 100 referencevalue myCircle AssignobjectreferencetomyCircle animation 21 TraceCode cont CirclemyCircle newCircle 5 0 CircleyourCircle newCircle yourCircle radius 100 referencevalue myCircle novalue yourCircle DeclareyourCircle animation 22 TraceCode cont CirclemyCircle newCircle 5 0 CircleyourCircle newCircle yourCircle radius 100 referencevalue myCircle novalue yourCircle CreateanewCircleobject animation 23 TraceCode cont CirclemyCircle newCircle 5 0 CircleyourCircle newCircle yourCircle radius 100 referencevalue myCircle referencevalue yourCircle AssignobjectreferencetoyourCircle animation 24 TraceCode cont CirclemyCircle newCircle 5 0 CircleyourCircle newCircle yourCircle radius 100 referencevalue myCircle referencevalue yourCircle ChangeradiusinyourCircle animation 25 Caution RecallthatyouuseMath methodName arguments e g Math pow 3 2 5 toinvokeamethodintheMathclass CanyouinvokegetArea usingCircle1 getArea Theanswerisno Allthemethodsusedbeforethischapterarestaticmethods whicharedefinedusingthestatickeyword However getArea isnon static ItmustbeinvokedfromanobjectusingobjectRefVar methodName arguments e g myCircle getArea Moreexplanationswillbegiveninthesectionon StaticVariables Constants andMethods 26 ReferenceDataFields Thedatafieldscanbeofreferencetypes Forexample thefollowingStudentclasscontainsadatafieldnameoftheStringtype publicclassStudent Stringname namehasdefaultvaluenullintage agehasdefaultvalue0booleanisScienceMajor isScienceMajorhasdefaultvaluefalsechargender chasdefaultvalue u0000 27 ThenullValue Ifadatafieldofareferencetypedoesnotreferenceanyobject thedatafieldholdsaspecialliteralvalue null 28 DefaultValueforaDataField Thedefaultvalueofadatafieldisnullforareferencetype 0foranumerictype falseforabooleantype and u0000 forachartype However Javaassignsnodefaultvaluetoalocalvariableinsideamethod publicclassTest publicstaticvoidmain String args Studentstudent newStudent System out println name student name System out println age student age System out println isScienceMajor student isScienceMajor System out println gender student gender 29 Example publicclassTest publicstaticvoidmain String args intx xhasnodefaultvalueStringy yhasnodefaultvalueSystem out println xis x System out println yis y Compilationerror variablesnotinitialized Javaassignsnodefaultvaluetoalocalvariableinsideamethod 30 DifferencesbetweenVariablesofPrimitiveDataTypesandObjectTypes 31 CopyingVariablesofPrimitiveDataTypesandObjectTypes 32 GarbageCollection Asshowninthepreviousfigure aftertheassignmentstatementc1 c2 c1pointstothesameobjectreferencedbyc2 Theobjectpreviouslyreferencedbyc1isnolongerreferenced Thisobjectisknownasgarbage GarbageisautomaticallycollectedbyJVM 33 GarbageCollection cont TIP Ifyouknowthatanobjectisnolongerneeded youcanexplicitlyassignnulltoareferencevariablefortheobject TheJVMwillautomaticallycollectthespaceiftheobjectisnotreferencedbyanyvariable 34 TheDateClass Javaprovidesasystem independentencapsulationofdateandtimeinthejava util Dateclass YoucanusetheDateclasstocreateaninstanceforthecurrentdateandtimeanduseitstoStringmethodtoreturnthedateandtimeasastring 35 TheDateClassExample Forexample thefollowingcodejava util Datedate newjava util Date System out println date toString displaysastringlikeSunMar0913 50 19EST2003 36 TheRandomClass YouhaveusedMath random toobtainarandomdoublevaluebetween0 0and1 0 excluding1 0 Amoreusefulrandomnumbergeneratorisprovidedinthejava util Randomclass 37 TheRandomClassExample IftwoRandomobjectshavethesameseed theywillgenerateidenticalsequencesofnumbers Forexample thefollowingcodecreatestwoRandomobjectswiththesameseed3 Randomrandom1 newRandom 3 System out print Fromrandom1 for inti 0 i 10 i System out print random1 nextInt 1000 Randomrandom2 newRandom 3 System out print nFromrandom2 for inti 0 i 10 i System out print random2 nextInt 1000 Fromrandom1 734660210581128202549564459961Fromrandom2 734660210581128202549564459961 38 DisplayingGUIComponents Whenyoudevelopprogramstocreategraphicaluserinterfaces youwilluseJavaclassessuchasJFrame JButton JRadioButton JComboBox andJListtocreateframes buttons radiobuttons comboboxes lists andsoon HereisanexamplethatcreatestwowindowsusingtheJFrameclass TestFrame Run 39 TraceCode JFrameframe1 newJFrame frame1 setTitle Window1 frame1 setSize 200 150 frame1 setVisible true JFrameframe2 newJFrame frame2 setTitle Window2 frame2 setSize 200 150 frame2 setVisible true Declare create andassigninonestatement reference frame1 JFrametitle width height visible animation 40 TraceCode JFrameframe1 newJFrame frame1 setTitle Window1 frame1 setSize 200 150 frame1 setVisible true JFrameframe2 newJFrame frame2 setTitle Window2 frame2 setSize 200 150 frame2 setVisible true reference frame1 JFrametitle Window1 width height visible Settitleproperty animation 41 TraceCode JFrameframe1 newJFrame frame1 setTitle Window1 frame1 setSize 200 150 frame1 setVisible true JFrameframe2 newJFrame frame2 setTitle Window2 frame2 setSize 200 150 frame2 setVisible true reference frame1 JFrametitle Window1 width 200height 150visible Setsizeproperty animation 42 TraceCode JFrameframe1 newJFrame frame1 setTitle Window1 frame1 setSize 200 150 frame1 setVisible true JFrameframe2 newJFrame frame2 setTitle Window2 frame2 setSize 200 150 frame2 setVisible true reference frame1 JFrametitle Window1 width 200height 150visible true Setvisibleproperty animation 43 TraceCode JFrameframe1 newJFrame frame1 setTitle Window1 frame1 setSize 200 150 frame1 setVisible true JFrameframe2 newJFrame frame2 setTitle Window2 frame2 setSize 200 150 frame2 setVisible true reference frame1 JFrametitle Window1 width 200height 150visible true Declare create andassigninonestatement reference frame2 JFrametitle width height visible animation 44 TraceCode JFrameframe1 newJFrame frame1 setTitle Window1 frame1 setSize 200 150 frame1 setVisible true JFrameframe2 newJFrame frame2 setTitle Window2 frame2 setSize 200 150 frame2 setVisible true reference frame1 JFrametitle Window1 width 200height 150visible true reference frame2 JFrametitle Window2 width height visible Settitleproperty animation 45 TraceCode JFrameframe1 newJFrame frame1 setTitle Window1 frame1 setSize 200 150 frame1 setVisible true JFrameframe2 newJFrame frame2 setTitle Window2 frame2 setSize 200 150 frame2 setVisible true reference frame1 JFrametitle Window1 width 200height 150visible true reference frame2 JFrametitle Window2 width 200height 150visible Setsizeproperty animation 46 TraceCode JFrameframe1 newJFrame frame1 setTitle Window1 frame1 setSize 200 150 frame1 setVisible true JFrameframe2 newJFrame frame2 setTitle Window2 frame2 setSize 200 150 frame2 setVisible true reference frame1 JFrametitle Window1 width 200height 150visible true reference frame2 JFrametitle Window2 width 200height 150visible true Setvisibleproperty animation 47 AddingGUIComponentstoWindow Youcanaddgraphicaluserinterfacecomponents suchasbuttons labels textfields comboboxes lists andmenus tothewindow Thecomponentsaredefinedusingclasses Hereisanexampletocreatebuttons labels textfields checkboxes radiobuttons andcomboboxes GUIComponents Run 48 InstanceVariables andMethods Instancevariablesbelongtoaspecificinstance Instancemethodsareinvokedbyaninstanceoftheclass 49 StaticVariables Constants andMethods Staticvariablesaresharedbyalltheinstancesoftheclass Staticmethodsarenottiedtoaspecificobject Staticconstantsarefinalvariablessharedbyalltheinstancesoftheclass 50 StaticVariables Constants andMethods cont Todeclarestaticvariables constants andmethods usethestaticmodifier 51 StaticVariables Constants andMethods cont 52 ExampleofUsingInstanceandClassVariablesandMethod Objective Demonstratetherolesofinstanceandclassvariablesandtheiruses ThisexampleaddsaclassvariablenumberOfObjectstotrackthenumberofCircleobjectscreated TestCircle2 Run Circle2 53

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论