- 749.00 KB
- 2022-04-29 14:26:13 发布
- 1、本文档共5页,可阅读全部内容。
- 2、本文档内容版权归属内容提供方,所产生的收益全部归内容提供方所有。如果您对本文有版权争议,可选择认领,认领后既往收益都归您。
- 3、本文档由用户上传,本站不保证质量和数量令人满意,可能有诸多瑕疵,付费之前,请仔细先通过免费阅读内容等途径辨别内容交易风险。如存在严重挂羊头卖狗肉之情形,可联系本站下载客服投诉处理。
- 文档侵权举报电话:19940600175。
'1Chapter8ObjectsandClasses
2MotivationsAfterlearningtheprecedingchapters,youarecapableofsolvingmanyprogrammingproblemsusingselections,loops,methods,andarrays.However,theseJavafeaturesarenotsufficientfordevelopinggraphicaluserinterfacesandlargescalesoftwaresystems.Supposeyouwanttodevelopagraphicaluserinterfaceasshownbelow.Howdoyouprogramit?
3ObjectivesTodescribeobjectsandclasses,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).
4OOProgrammingConceptsObject-orientedprogramming(OOP)involvesprogrammingusingobjects.Anobjectrepresentsanentityintherealworldthatcanbedistinctlyidentified.Forexample,astudent,adesk,acircle,abutton,andevenaloancanallbeviewedasobjects.Anobjecthasauniqueidentity,state,andbehaviors.Thestateofanobjectconsistsofasetofdatafields(alsoknownasproperties)withtheircurrentvalues.Thebehaviorofanobjectisdefinedbyasetofmethods.
5ObjectsAnobjecthasbothastateandbehavior.Thestatedefinestheobject,andthebehaviordefineswhattheobjectdoes.
6ClassesClassesareconstructsthatdefineobjectsofthesametype.AJavaclassusesvariablestodefinedatafieldsandmethodstodefinebehaviors.Additionally,aclassprovidesaspecialtypeofmethods,knownasconstructors,whichareinvokedtoconstructobjectsfromtheclass.
7Classes
8UMLClassDiagram
9Example:DefiningClassesandCreatingObjectsObjective:Demonstratecreatingobjects,accessingdata,andusingmethods.TestCircle1Run
10Example:DefiningClassesandCreatingObjectsObjective:Demonstratecreatingobjects,accessingdata,andusingmethods.TestTVRunTV
11ConstructorsCircle(){}Circle(doublenewRadius){radius=newRadius;}Constructorsareaspecialkindofmethodsthatareinvokedtoconstructobjects.
12Constructors,cont.Aconstructorwithnoparametersisreferredtoasano-argconstructor.· Constructorsmusthavethesamenameastheclassitself.· Constructorsdonothaveareturntype—notevenvoid.· Constructorsareinvokedusingthenewoperatorwhenanobjectiscreated.Constructorsplaytheroleofinitializingobjects.
13CreatingObjectsUsingConstructorsnewClassName();Example:newCircle();newCircle(5.0);
14DefaultConstructorAclassmaybedeclaredwithoutconstructors.Inthiscase,ano-argconstructorwithanemptybodyisimplicitlydeclaredintheclass.Thisconstructor,calledadefaultconstructor,isprovidedautomaticallyonlyifnoconstructorsareexplicitlydeclaredintheclass.
15DeclaringObjectReferenceVariablesToreferenceanobject,assigntheobjecttoareferencevariable.Todeclareareferencevariable,usethesyntax:ClassNameobjectRefVar;Example:CirclemyCircle;
16Declaring/CreatingObjectsinaSingleStepClassNameobjectRefVar=newClassName();Example:CirclemyCircle=newCircle();CreateanobjectAssignobjectreference
17AccessingObjectsReferencingtheobject’sdata:objectRefVar.datae.g.,myCircle.radiusInvokingtheobject’smethod:objectRefVar.methodName(arguments)e.g.,myCircle.getArea()
18TraceCodeCirclemyCircle=newCircle(5.0);SCircleyourCircle=newCircle();yourCircle.radius=100;DeclaremyCirclenovaluemyCircleanimation
19TraceCode,cont.CirclemyCircle=newCircle(5.0);CircleyourCircle=newCircle();yourCircle.radius=100;novaluemyCircleCreateacircleanimation
20TraceCode,cont.CirclemyCircle=newCircle(5.0);CircleyourCircle=newCircle();yourCircle.radius=100;referencevaluemyCircleAssignobjectreferencetomyCircleanimation
21TraceCode,cont.CirclemyCircle=newCircle(5.0);CircleyourCircle=newCircle();yourCircle.radius=100;referencevaluemyCirclenovalueyourCircleDeclareyourCircleanimation
22TraceCode,cont.CirclemyCircle=newCircle(5.0);CircleyourCircle=newCircle();yourCircle.radius=100;referencevaluemyCirclenovalueyourCircleCreateanewCircleobjectanimation
23TraceCode,cont.CirclemyCircle=newCircle(5.0);CircleyourCircle=newCircle();yourCircle.radius=100;referencevaluemyCirclereferencevalueyourCircleAssignobjectreferencetoyourCircleanimation
24TraceCode,cont.CirclemyCircle=newCircle(5.0);CircleyourCircle=newCircle();yourCircle.radius=100;referencevaluemyCirclereferencevalueyourCircleChangeradiusinyourCircleanimation
25CautionRecallthatyouuseMath.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.”
26ReferenceDataFieldsThedatafieldscanbeofreferencetypes.Forexample,thefollowingStudentclasscontainsadatafieldnameoftheStringtype.publicclassStudent{Stringname;//namehasdefaultvaluenullintage;//agehasdefaultvalue0booleanisScienceMajor;//isScienceMajorhasdefaultvaluefalsechargender;//chasdefaultvalue"u0000"}
27ThenullValueIfadatafieldofareferencetypedoesnotreferenceanyobject,thedatafieldholdsaspecialliteralvalue,null.
28DefaultValueforaDataFieldThedefaultvalueofadatafieldisnullforareferencetype,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);}}
29ExamplepublicclassTest{publicstaticvoidmain(String[]args){intx;//xhasnodefaultvalueStringy;//yhasnodefaultvalueSystem.out.println("xis"+x);System.out.println("yis"+y);}}Compilationerror:variablesnotinitializedJavaassignsnodefaultvaluetoalocalvariableinsideamethod.
30DifferencesbetweenVariablesofPrimitiveDataTypesandObjectTypes
31CopyingVariablesofPrimitiveDataTypesandObjectTypes
32GarbageCollectionAsshowninthepreviousfigure,aftertheassignmentstatementc1=c2,c1pointstothesameobjectreferencedbyc2.Theobjectpreviouslyreferencedbyc1isnolongerreferenced.Thisobjectisknownasgarbage.GarbageisautomaticallycollectedbyJVM.
33GarbageCollection,contTIP:Ifyouknowthatanobjectisnolongerneeded,youcanexplicitlyassignnulltoareferencevariablefortheobject.TheJVMwillautomaticallycollectthespaceiftheobjectisnotreferencedbyanyvariable.
34TheDateClassJavaprovidesasystem-independentencapsulationofdateandtimeinthejava.util.Dateclass.YoucanusetheDateclasstocreateaninstanceforthecurrentdateandtimeanduseitstoStringmethodtoreturnthedateandtimeasastring.
35TheDateClassExampleForexample,thefollowingcodejava.util.Datedate=newjava.util.Date();System.out.println(date.toString());displaysastringlikeSunMar0913:50:19EST2003.
36TheRandomClassYouhaveusedMath.random()toobtainarandomdoublevaluebetween0.0and1.0(excluding1.0).Amoreusefulrandomnumbergeneratorisprovidedinthejava.util.Randomclass.
37TheRandomClassExampleIftwoRandomobjectshavethesameseed,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
38DisplayingGUIComponentsWhenyoudevelopprogramstocreategraphicaluserinterfaces,youwilluseJavaclassessuchasJFrame,JButton,JRadioButton,JComboBox,andJListtocreateframes,buttons,radiobuttons,comboboxes,lists,andsoon.HereisanexamplethatcreatestwowindowsusingtheJFrameclass.TestFrameRun
39TraceCodeJFrameframe1=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,andassigninonestatementreferenceframe1:JFrametitle:width:height:visible:animation
40TraceCodeJFrameframe1=newJFrame();frame1.setTitle("Window1");frame1.setSize(200,150);frame1.setVisible(true);JFrameframe2=newJFrame();frame2.setTitle("Window2");frame2.setSize(200,150);frame2.setVisible(true);referenceframe1:JFrametitle:"Window1"width:height:visible:Settitlepropertyanimation
41TraceCodeJFrameframe1=newJFrame();frame1.setTitle("Window1");frame1.setSize(200,150);frame1.setVisible(true);JFrameframe2=newJFrame();frame2.setTitle("Window2");frame2.setSize(200,150);frame2.setVisible(true);referenceframe1:JFrametitle:"Window1"width:200height:150visible:Setsizepropertyanimation
42TraceCodeJFrameframe1=newJFrame();frame1.setTitle("Window1");frame1.setSize(200,150);frame1.setVisible(true);JFrameframe2=newJFrame();frame2.setTitle("Window2");frame2.setSize(200,150);frame2.setVisible(true);referenceframe1:JFrametitle:"Window1"width:200height:150visible:trueSetvisiblepropertyanimation
43TraceCodeJFrameframe1=newJFrame();frame1.setTitle("Window1");frame1.setSize(200,150);frame1.setVisible(true);JFrameframe2=newJFrame();frame2.setTitle("Window2");frame2.setSize(200,150);frame2.setVisible(true);referenceframe1:JFrametitle:"Window1"width:200height:150visible:trueDeclare,create,andassigninonestatementreferenceframe2:JFrametitle:width:height:visible:animation
44TraceCodeJFrameframe1=newJFrame();frame1.setTitle("Window1");frame1.setSize(200,150);frame1.setVisible(true);JFrameframe2=newJFrame();frame2.setTitle("Window2");frame2.setSize(200,150);frame2.setVisible(true);referenceframe1:JFrametitle:"Window1"width:200height:150visible:truereferenceframe2:JFrametitle:"Window2"width:height:visible:Settitlepropertyanimation
45TraceCodeJFrameframe1=newJFrame();frame1.setTitle("Window1");frame1.setSize(200,150);frame1.setVisible(true);JFrameframe2=newJFrame();frame2.setTitle("Window2");frame2.setSize(200,150);frame2.setVisible(true);referenceframe1:JFrametitle:"Window1"width:200height:150visible:truereferenceframe2:JFrametitle:"Window2"width:200height:150visible:Setsizepropertyanimation
46TraceCodeJFrameframe1=newJFrame();frame1.setTitle("Window1");frame1.setSize(200,150);frame1.setVisible(true);JFrameframe2=newJFrame();frame2.setTitle("Window2");frame2.setSize(200,150);frame2.setVisible(true);referenceframe1:JFrametitle:"Window1"width:200height:150visible:truereferenceframe2:JFrametitle:"Window2"width:200height:150visible:trueSetvisiblepropertyanimation
47AddingGUIComponentstoWindowYoucanaddgraphicaluserinterfacecomponents,suchasbuttons,labels,textfields,comboboxes,lists,andmenus,tothewindow.Thecomponentsaredefinedusingclasses.Hereisanexampletocreatebuttons,labels,textfields,checkboxes,radiobuttons,andcomboboxes.GUIComponentsRun
48InstanceVariables,andMethodsInstancevariablesbelongtoaspecificinstance.Instancemethodsareinvokedbyaninstanceoftheclass.
49StaticVariables,Constants,andMethodsStaticvariablesaresharedbyalltheinstancesoftheclass.Staticmethodsarenottiedtoaspecificobject.Staticconstantsarefinalvariablessharedbyalltheinstancesoftheclass.
50StaticVariables,Constants,andMethods,cont.Todeclarestaticvariables,constants,andmethods,usethestaticmodifier.
51StaticVariables,Constants,andMethods,cont.
52ExampleofUsingInstanceandClassVariablesandMethodObjective:Demonstratetherolesofinstanceandclassvariablesandtheiruses.ThisexampleaddsaclassvariablenumberOfObjectstotrackthenumberofCircleobjectscreated.TestCircle2RunCircle2
53VisibilityModifiersandAccessor/MutatorMethodsBydefault,theclass,variable,ormethodcanbeaccessedbyanyclassinthesamepackage.publicTheclass,data,ormethodisvisibletoanyclassinanypackage.privateThedataormethodscanbeaccessedonlybythedeclaringclass.Thegetandsetmethodsareusedtoreadandmodifyprivateproperties.
54Theprivatemodifierrestrictsaccesstowithinaclass,thedefaultmodifierrestrictsaccesstowithinapackage,andthepublicmodifierenablesunrestrictedaccess.
55NOTEAnobjectcannotaccessitsprivatemembers,asshownin(b).ItisOK,however,iftheobjectisdeclaredinitsownclass,asshownin(a).
56WhyDataFieldsShouldBeprivate?Toprotectdata.Tomakeclasseasytomaintain.
57ExampleofDataFieldEncapsulationCircle3RunTestCircle3
58PassingObjectstoMethodsPassingbyvalueforprimitivetypevalue(thevalueispassedtotheparameter)Passingbyvalueforreferencetypevalue(thevalueisthereferencetotheobject)TestPassObjectRun
59PassingObjectstoMethods,cont.
60ArrayofObjectsCircle[]circleArray=newCircle[10];Anarrayofobjectsisactuallyanarrayofreferencevariables.SoinvokingcircleArray[1].getArea()involvestwolevelsofreferencingasshowninthenextfigure.circleArrayreferencestotheentirearray.circleArray[1]referencestoaCircleobject.
61ArrayofObjects,cont.Circle[]circleArray=newCircle[10];
62ArrayofObjects,cont.SummarizingtheareasofthecirclesTotalAreaRun
服务理念中的“点点”◆理解多一点真情浓一点◆学习勤一点品质高一点◆理由少一点效率高一点◆处理问题灵活点工作过程用心点◆对待同事宽容点互相协作快乐点
放映结束!敬请各位的批评指导!谢谢观看'
您可能关注的文档
- 电商物流课件PPT
- 西师版四年级下学期数学《小数点位置移动引起小数大小的变化课件PPT》
- 人教版小学数学一年级下册《找规律》课件PPT-(1)
- 景阳冈课件PPT
- 游戏公平课件PPT下载北师大版四年级数学下册课件
- 爱迪生救妈妈》课件PPT
- 画里阴晴 优秀课件PPT
- 火烧云优秀课件PPT
- CAN网络控制器及相关芯片教学课件PPT总线收发器
- 第9课《母鸡》2课件PPT
- 苏教版一年级上册数学《认识钟表》课件PPT
- 苏教版一年级上册数学《0的认识》公开课课件PPT
- 第三单元第12课《济南的冬天》要点课件PPT
- 苏教版三年级上册语文《石头书》公开课课件PPT
- 苏教版三年级上册语文《做一片美的叶子》公开课课件PPT
- 苏教版三年级下册数学《小数的意义和读写》课件PPT
- 苏教版五年级下册语文《火星——地球的孪生兄弟》课件PPT
- 苏教版五年级下册语文《司马迁发愤写《史记》课件PPT