版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1Chapter8ObjectsandClasses1Chapter8ObjectsandClasses2MotivationsAfterlearningtheprecedingchapters,youarecapableofsolvingmanyprogrammingproblemsusingselections,loops,methods,andarrays.However,theseJavafeaturesarenotsufficientfordevelopinggraphicaluserinterfacesandlargescalesoftwaresystems.Supposeyouwanttodevelopagraphicaluserinterfaceasshownbelow.Howdoyouprogramit?2MotivationsAfterlearningthe3ObjectivesTodescribeobjectsandclasses,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).3ObjectivesTodescribeobjects4OOProgrammingConceptsObject-orientedprogramming(OOP)involvesprogrammingusingobjects.Anobjectrepresentsanentityintherealworldthatcanbedistinctlyidentified.Forexample,astudent,adesk,acircle,abutton,andevenaloancanallbeviewedasobjects.Anobjecthasauniqueidentity,state,andbehaviors.Thestateofanobjectconsistsofasetofdata
fields(alsoknownasproperties)withtheircurrentvalues.Thebehaviorofanobjectisdefinedbyasetofmethods.4OOProgrammingConceptsObject5ObjectsAnobjecthasbothastateandbehavior.Thestatedefinestheobject,andthebehaviordefineswhattheobjectdoes.5ObjectsAnobjecthasbothas6ClassesClassesareconstructsthatdefineobjectsofthesametype.AJavaclassusesvariablestodefinedatafieldsandmethodstodefinebehaviors.Additionally,aclassprovidesaspecialtypeofmethods,knownasconstructors,whichareinvokedtoconstructobjectsfromtheclass.6ClassesClassesareconstructs7Classes7Classes8UMLClassDiagram8UMLClassDiagram9Example:DefiningClassesandCreatingObjectsObjective:Demonstratecreatingobjects,accessingdata,andusingmethods.
TestCircle1Run9Example:DefiningClassesand10Example:DefiningClassesandCreatingObjectsObjective:Demonstratecreatingobjects,accessingdata,andusingmethods.
TestTVRunTV10Example:DefiningClassesan11ConstructorsCircle(){}Circle(doublenewRadius){radius=newRadius;}Constructorsareaspecialkindofmethodsthatareinvokedtoconstructobjects.11ConstructorsCircle(){Constr12Constructors,cont.Aconstructorwithnoparametersisreferredtoasano-argconstructor.·
Constructorsmusthavethesamenameastheclassitself.·
Constructorsdonothaveareturntype—notevenvoid.·
Constructorsareinvokedusingthenewoperatorwhenanobjectiscreated.Constructorsplaytheroleofinitializingobjects.12Constructors,cont.Aconstru13CreatingObjectsUsingConstructorsnewClassName();Example:newCircle();newCircle(5.0);
13CreatingObjectsUsingConst14DefaultConstructorAclassmaybedeclaredwithoutconstructors.Inthiscase,ano-argconstructorwithanemptybodyisimplicitlydeclaredintheclass.Thisconstructor,calledadefaultconstructor,isprovidedautomaticallyonlyifnoconstructorsareexplicitlydeclaredintheclass.14DefaultConstructorAclassm15DeclaringObjectReferenceVariablesToreferenceanobject,assigntheobjecttoareferencevariable.Todeclareareferencevariable,usethesyntax:ClassNameobjectRefVar;Example:CirclemyCircle;15DeclaringObjectReferenceV16Declaring/CreatingObjects
inaSingleStepClassNameobjectRefVar=newClassName();Example:CirclemyCircle=newCircle();CreateanobjectAssignobjectreference
16Declaring/CreatingObjects
i17AccessingObjectsReferencingtheobject’sdata:
objectRefVar.datae.g.,myCircle.radiusInvokingtheobject’smethod:
objectRefVar.methodName(arguments)e.g.,myCircle.getArea()17AccessingObjectsReferencing18TraceCodeCirclemyCircle=newCircle(5.0);SCircleyourCircle=newCircle();yourCircle.radius=100;DeclaremyCirclenovaluemyCircleanimation18TraceCodeCirclemyCircle=19TraceCode,cont.CirclemyCircle=newCircle(5.0);CircleyourCircle=newCircle();yourCircle.radius=100;novaluemyCircleCreateacircleanimation19TraceCode,cont.CirclemyCi20TraceCode,cont.CirclemyCircle=newCircle(5.0);CircleyourCircle=newCircle();yourCircle.radius=100;referencevaluemyCircleAssignobjectreferencetomyCircleanimation20TraceCode,cont.CirclemyCi21TraceCode,cont.CirclemyCircle=newCircle(5.0);CircleyourCircle=newCircle();yourCircle.radius=100;referencevaluemyCirclenovalueyourCircleDeclareyourCircleanimation21TraceCode,cont.CirclemyCi22TraceCode,cont.CirclemyCircle=newCircle(5.0);CircleyourCircle=newCircle();yourCircle.radius=100;referencevaluemyCirclenovalueyourCircleCreateanewCircleobjectanimation22TraceCode,cont.CirclemyCi23TraceCode,cont.CirclemyCircle=newCircle(5.0);CircleyourCircle=newCircle();yourCircle.radius=100;referencevaluemyCirclereferencevalueyourCircleAssignobjectreferencetoyourCircleanimation23TraceCode,cont.CirclemyCi24TraceCode,cont.CirclemyCircle=newCircle(5.0);CircleyourCircle=newCircle();yourCircle.radius=100;referencevaluemyCirclereferencevalueyourCircleChangeradiusinyourCircleanimation24TraceCode,cont.CirclemyCi25CautionRecallthatyouuseMath.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.”25CautionRecallthatyouuse26ReferenceDataFieldsThedatafieldscanbeofreferencetypes.Forexample,thefollowingStudentclasscontainsadatafieldnameoftheStringtype.publicclassStudent{Stringname;//namehasdefaultvaluenullintage;//agehasdefaultvalue0booleanisScienceMajor;//isScienceMajorhasdefaultvaluefalsechargender;//chasdefaultvalue'\u0000'}26ReferenceDataFieldsThedat27ThenullValueIfadatafieldofareferencetypedoesnotreferenceanyobject,thedatafieldholdsaspecialliteralvalue,null.27ThenullValueIfadatafiel28DefaultValueforaDataFieldThedefaultvalueofadatafieldisnullforareferencetype,0foranumerictype,falseforabooleantype,and'\u0000'forachartype.However,Javaassignsnodefaultvaluetoalocalvariableinsideamethod.publicclassTest{publicstaticvoidmain(String[]args){Studentstudent=newStudent();System.out.println("name?"+);System.out.println("age?"+student.age);System.out.println("isScienceMajor?"+student.isScienceMajor);System.out.println("gender?"+student.gender);}}28DefaultValueforaDataFie29ExamplepublicclassTest{publicstaticvoidmain(String[]args){intx;//xhasnodefaultvalueStringy;//yhasnodefaultvalueSystem.out.println("xis"+x);System.out.println("yis"+y);}}Compilationerror:variablesnotinitializedJavaassignsnodefaultvaluetoalocalvariableinsideamethod.29ExamplepublicclassTest{Co30DifferencesbetweenVariablesof
PrimitiveDataTypesandObjectTypes
30DifferencesbetweenVariable31CopyingVariablesofPrimitiveDataTypesandObjectTypes31CopyingVariablesofPrimiti32GarbageCollectionAsshowninthepreviousfigure,aftertheassignmentstatementc1=c2,c1pointstothesameobjectreferencedbyc2.Theobjectpreviouslyreferencedbyc1isnolongerreferenced.Thisobjectisknownasgarbage.GarbageisautomaticallycollectedbyJVM.32GarbageCollectionAsshowni33GarbageCollection,cont
TIP:Ifyouknowthatanobjectisnolongerneeded,youcanexplicitlyassignnulltoareferencevariablefortheobject.TheJVMwillautomaticallycollectthespaceiftheobjectisnotreferencedbyanyvariable.33GarbageCollection,contTIP34TheDateClassJavaprovidesasystem-independentencapsulationofdateandtimeinthejava.util.Dateclass.YoucanusetheDateclasstocreateaninstanceforthecurrentdateandtimeanduseitstoStringmethodtoreturnthedateandtimeasastring.34TheDateClassJavaprovides35TheDateClassExampleForexample,thefollowingcode
java.util.Datedate=newjava.util.Date();System.out.println(date.toString());displaysastringlike
SunMar0913:50:19EST2003.35TheDateClassExampleForex36TheRandomClassYouhaveusedMath.random()toobtainarandomdoublevaluebetween0.0and1.0(excluding1.0).Amoreusefulrandomnumbergeneratorisprovidedinthejava.util.Randomclass.36TheRandomClassYouhaveuse37TheRandomClassExampleIftwoRandomobjectshavethesameseed,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:73466021058112820254956445996137TheRandomClassExampleIft38DisplayingGUIComponentsWhenyoudevelopprogramstocreategraphicaluserinterfaces,youwilluseJavaclassessuchasJFrame,JButton,JRadioButton,JComboBox,andJListtocreateframes,buttons,radiobuttons,comboboxes,lists,andsoon.HereisanexamplethatcreatestwowindowsusingtheJFrameclass.TestFrameRun38DisplayingGUIComponentsWhe39TraceCodeJFrameframe1=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:animation39TraceCodeJFrameframe1=ne40TraceCodeJFrameframe1=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:Settitlepropertyanimation40TraceCodeJFrameframe1=ne41TraceCodeJFrameframe1=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:Setsizepropertyanimation41TraceCodeJFrameframe1=ne42TraceCodeJFrameframe1=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:trueSetvisiblepropertyanimation42TraceCodeJFrameframe1=ne43TraceCodeJFrameframe1=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:animation43TraceCodeJFrameframe1=ne44TraceCodeJFrameframe1=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:Settitlepropertyanimation44TraceCodeJFrameframe1=ne45TraceCodeJFrameframe1=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:Setsizepropertyanimation45TraceCodeJFrameframe1=ne46TraceCodeJFrameframe1=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:trueSetvisiblepropertyanimation46TraceCodeJFrameframe1=ne47AddingGUIComponentstoWindowYoucanaddgraphicaluserinterfacecomponents,suchasbuttons,labels,textfields,comboboxes,lists,andmenus,tothewindow.Thecomponentsaredefinedusingclasses.Hereisanexampletocreatebuttons,labels,textfields,checkboxes,radiobuttons,andcomboboxes.GUIComponentsRun47AddingGUIComponentstoWin48Instance
Variables,andMethods
Instancevariablesbelongtoaspecificinstance.
Instancemethodsareinvokedbyaninstanceoftheclass.48Instance
Variables,andMe49StaticVariables,Constants,
andMethodsStaticvariablesaresharedbyalltheinstancesoftheclass.
Staticmethodsarenottiedtoaspecificobject.Staticconstantsarefinalvariablessharedbyalltheinstancesoftheclass.49StaticVariables,Constants,50StaticVariables,Constants,
andMethods,cont.Todeclarestaticvariables,constants,andmethods,usethestaticmodifier.50StaticVariables,Constants,51StaticVariables,Constants,
andMethods,cont.51StaticVariables,Constants,52Exampleof
UsingInstanceandClassVariablesandMethodObjective:Demonstratetherolesofinstanceandclassvariablesandtheiruses.ThisexampleaddsaclassvariablenumberOfObjectstotrackthenumberofCircleobjectscreated.
TestCircle2RunCircle252Exampleof
UsingInstancean53VisibilityModifiersand
Accessor/MutatorMethodsBydefault,theclass,variable,ormethodcanbe
accessedbyanyclassinthesamepackage.
public Theclass,data,ormethodisvisibletoanyclassinanypackage.private
Thedataormethodscanbeaccessedonlybythedeclaringclass.Thegetandsetmethodsareusedtoreadandmodifyprivateproperties. 53VisibilityModifiersand
Ac54Theprivatemodifierrestrictsaccesstowithinaclass,thedefaultmodifierrestrictsaccesstowithinapackage,andthepublicmodifierenablesunrestrictedaccess.
54Theprivatemodifierrestric55NOTEAnobjectcannotaccessitsprivatemembers,asshownin(b).ItisOK,however,iftheobjectisdeclaredinitsownclass,asshownin(a).
55NOTEAnobjectcannotaccess56WhyDataFieldsShouldBeprivate?Toprotectdata.Tomakeclasseasytomaintain.
56WhyDataFieldsShouldBepr57Exampleof
DataFieldEncapsulationCircle3RunTestCircle357Exampleof
DataFieldEncaps58PassingObjectstoMethodsPassingbyvalueforprimitivetypevalue(thevalueispassedtotheparameter)Passingbyvalueforreferencetypevalue(thevalueisthereferencetotheobject)TestPassObjectRun58PassingObjectstoMethodsPa59PassingObjectstoMethods,cont.59PassingObjectstoMethods,60ArrayofObjectsCircle[]circleArray=newCircle[10];
Anarrayofobjectsisactuallyanarrayofreferencevariables.SoinvokingcircleArray[1].getArea()involvestwolevelsofreferencingasshowninthenextfigure.circleArrayreferencestotheentirearray.circleArray[1]referencestoaCircleobject.
60ArrayofObjectsCircle[]ci61ArrayofObjects,cont.Circle[]circleArray=newCircle[10];
61ArrayofObjects,cont.Ci62ArrayofObjects,cont.Summarizingtheareasofthecircles
TotalAreaRun62ArrayofObjects,cont.Summa63Chapter8ObjectsandClasses1Chapter8ObjectsandClasses64MotivationsAfterlearningtheprecedingchapters,youarecapableofsolvingmanyprogrammingproblemsusingselections,loops,methods,andarrays.However,theseJavafeaturesarenotsufficientfordevelopinggraphicaluserinterfacesandlargescalesoftwaresystems.Supposeyouwanttodevelopagraphicaluserinterfaceasshownbelow.Howdoyouprogramit?2MotivationsAfterlearningthe65ObjectivesTodescribeobjectsandclasses,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).3ObjectivesTodescribeobjects66OOProgrammingConceptsObject-orientedprogramming(OOP)involvesprogrammingusingobjects.Anobjectrepresentsanentityintherealworldthatcanbedistinctlyidentified.Forexample,astudent,adesk,acircle,abutton,andevenaloancanallbeviewedasobjects.Anobjecthasauniqueidentity,state,andbehaviors.Thestateofanobjectconsistsofasetofdata
fields(alsoknownasproperties)withtheircurrentvalues.Thebehaviorofanobjectisdefinedbyasetofmethods.4OOProgrammingConceptsObject67ObjectsAnobjecthasbothastateandbehavior.Thestatedefinestheobject,andthebehaviordefineswhattheobjectdoes.5ObjectsAnobjecthasbothas68ClassesClassesareconstructsthatdefineobjectsofthesametype.AJavaclassusesvariablestodefinedatafieldsandmethodstodefinebehaviors.Additionally,aclassprovidesaspecialtypeofmethods,knownasconstructors,whichareinvokedtoconstructobjectsfromtheclass.6ClassesClassesareconstructs69Classes7Classes70UMLClassDiagram8UMLClassDiagram71Example:DefiningClassesandCreatingObjectsObjective:Demonstratecreatingobjects,accessingdata,andusingmethods.
TestCircle1Run9Example:DefiningClassesand72Example:DefiningClassesandCreatingObjectsObjective:Demonstratecreatingobjects,accessingdata,andusingmethods.
TestTVRunTV10Example:DefiningClassesan73ConstructorsCircle(){}Circle(doublenewRadius){radius=newRadius;}Constructorsareaspecialkindofmethodsthatareinvokedtoconstructobjects.11ConstructorsCircle(){Constr74Constructors,cont.Aconstructorwithnoparametersisreferredtoasano-argconstructor.·
Constructorsmusthavethesamenameastheclassitself.·
Constructorsdonothaveareturntype—notevenvoid.·
Constructorsareinvokedusingthenewoperatorwhenanobjectiscreated.Constructorsplaytheroleofinitializingobjects.12Constructors,cont.Aconstru75CreatingObjectsUsingConstructorsnewClassName();Example:newCircle();newCircle(5.0);
13CreatingObjectsUsingConst76DefaultConstructorAclassmaybedeclaredwithoutconstructors.Inthiscase,ano-argconstructorwithanemptybodyisimplicitlydeclaredintheclass.Thisconstructor,calledadefaultconstructor,isprovidedautomaticallyonlyifnoconstructorsareexplicitlydeclaredintheclass.14DefaultConstructorAclassm77DeclaringObjectReferenceVariablesToreferenceanobject,assigntheobjecttoareferencevariable.Todeclareareferencevariable,usethesyntax:ClassNameobjectRefVar;Example:CirclemyCircle;15DeclaringObjectReferenceV78Declaring/CreatingObjects
inaSingleStepClassNameobjectRefVar=newClassName();Example:CirclemyCircle=newCircle();CreateanobjectAssignobjectreference
16Declaring/CreatingObjects
i79AccessingObjectsReferencingtheobject’sdata:
objectRefVar.datae.g.,myCircle.radiusInvokingtheobject’smethod:
objectRefVar.methodName(arguments)e.g.,myCircle.getArea()17AccessingObjectsReferencing80TraceCodeCirclemyCircle=newCircle(5.0);SCircleyourCircle=newCircle();yourCircle.radius=100;DeclaremyCirclenovaluemyCircleanimation18TraceCodeCirclemyCircle=81TraceCode,cont.CirclemyCircle=newCircle(5.0);CircleyourCircle=newCircle();yourCircle.radius=100;novaluemyCircleCreateacircleanimation19TraceCode,cont.CirclemyCi82TraceCode,cont.CirclemyCircle=newCircle(5.0);CircleyourCircle=newCircle();yourCircle.radius=100;referencevaluemyCircleAssignobjectreferencetomyCircleanimation20TraceCode,cont.CirclemyCi83TraceCode,cont.CirclemyCircle=newCircle(5.0);CircleyourCircle=newCircle();yourCircle.radius=100;referencevaluemyCirclenovalueyourCircleDeclareyourCircleanimation21TraceCode,cont.CirclemyCi84TraceCode,cont.CirclemyCircle=newCircle(5.0);CircleyourCircle=newCircle();yourCircle.radius=100;referencevaluemyCirclenovalueyourCircleCreateanewCircleobjectanimation22TraceCode,cont.CirclemyCi85TraceCode,cont.CirclemyCircle=newCircle(5.0);CircleyourCircle=newCircle();yourCircle.radius=100;referencevaluemyCirclereferencevalueyourCircleAssignobjectreferencetoyourCircleanimation23TraceCode,cont.CirclemyCi86TraceCode,cont.CirclemyCircle=newCircle(5.0);CircleyourCircle=newCircle();yourCircle.radius=100;referencevaluemyCirclereferencevalueyourCircleChangeradiusinyourCircleanimation24TraceCode,cont.CirclemyCi87CautionRecallthatyouuseMath.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.”25CautionRecallthatyouuse88ReferenceDataFieldsThedatafieldscanbeofreferencetypes.Forexample,thefollowingStudentclasscontainsadatafieldnameoftheStringtype.publicclassStudent{Stringname;//namehasdefaultvaluenullintage;//agehasdefaultvalue0booleanisScienceMajor;//isScienceMajorhasdefaultvaluefalsechargender;//chasdefaultvalue'\u0000'}26ReferenceDataFieldsThedat89ThenullValueIfadatafieldofareferencetypedoesnotreferenceanyobject,thedatafieldholdsaspecialliteralvalue,null.27ThenullValueIfadatafiel90DefaultValueforaDataFieldThedefaultvalueofadatafieldisnullforareferencetype,0foranumerictype,falseforabooleantype,and'\u0000'forachartype.However,Javaassignsnodefaultvaluetoalocalvariableinsideamethod.publicclassTest{publicstaticvoidmain(String[]args){Studentstudent=newStudent();System.out.println("name?"+);System.out.println("age?"+student.age);System.out.println("isScienceMajor?"+student.isScienceMajor);System.out.println("gender?"+student.gender);}}28DefaultValueforaDataFie91ExamplepublicclassTest{publicstaticvoidmain(String[]args){intx;//xhasnodefaultvalueStringy;//yhasnodefaultvalueSystem.out.println("xis"+x);System.out.println("yis"+y);}}Compilationerror:variablesnotinitializedJavaassignsnodefaultvaluetoalocalvariableinsideamethod.29ExamplepublicclassTest{Co92DifferencesbetweenVariablesof
PrimitiveDataTypesandObjectTypes
30DifferencesbetweenVariable93CopyingVariablesofPrimitiveDataTypesandObjectTypes31CopyingVariablesofPrimiti94GarbageCollectionAsshowninthepreviousfigure,aftertheassignmentstatementc1=c2,c1pointstothesameobjectreferencedbyc2.Theobjectpreviouslyreferencedbyc1isnolongerreferenced.Thisobjectisknownasgarbage.GarbageisautomaticallycollectedbyJVM.32GarbageCollectionAsshowni95GarbageCollection,cont
TIP:Ifyouknowthatanobjectisnolongerneeded,youcanexplicitlyassignnulltoareferencevariablefortheobject.TheJVMwillautomaticallycollectthespaceiftheobjectisnotreferencedbyanyvariable.33GarbageCollection,cont
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2026社招mfc面试题及答案
- 2026施工班长面试题目及答案
- 风湿免疫科护理典型案例分享
- 安徽金太阳联盟考试试题及答案
- 2026年银行服务礼仪考试试题及答案及答案
- 2026年高校政治老师考试试题及答案
- 小学教师返城模拟考试试题及答案
- 《高中数学条件概率课|理解概念 掌握计算》
- 政治经济生活|供求价格 理解市场机制
- 流体输配管网Ch枝状管网水力工况分析与调节
- 美的集团第-级公司分权手册
- 画法几何及土木工程制图课件
- 机械设备的润滑课件
- 国开电大本科《理工英语4》机考总题库
- 门式启闭机主梁下主梁1工艺设计卡
- 管理者如何带好团队
- 人教版四年级下册数学期末测试卷(模拟题)
- 人教版数学必修一课后习题答案
- YS/T 1018-2015铼粒
- GB/T 27941-2011多联式空调(热泵)机组应用设计与安装要求
- 2023年天津市高考语文模拟试卷试题原创(含答案详解)
评论
0/150
提交评论