




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
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. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025版吊车租赁与现场安全防护措施合同
- 2025版航空航天孵化基地入驻技术支持合同
- 2025版个人信用担保合同类型与信贷风险管理
- 2025版虚拟现实孵化器场地租赁与沉浸式体验服务合同
- 2025版亮化工程照明控制系统集成合同
- 2025版国际贸易信用证合同条款及操作规范
- 二零二五年度电子商务平台数据分析服务合同汇编
- 二零二五版建筑施工现场临时消防安全检查合同
- 二零二五年度家庭关系调整-夫妻分居协议
- 二零二五版企业标识标牌设计与施工合同
- GB/T 18380.11-2022电缆和光缆在火焰条件下的燃烧试验第11部分:单根绝缘电线电缆火焰垂直蔓延试验试验装置
- GB/T 18342-2009链条炉排锅炉用煤技术条件
- GB/T 14502-1993水中镍-63的分析方法
- GB/T 12706.1-2020额定电压1 kV(Um=1.2 kV)到35 kV(Um=40.5 kV)挤包绝缘电力电缆及附件第1部分:额定电压1 kV(Um=1.2 kV)和3 kV(Um=3.6 kV)电缆
- 国际航标协会海上浮标制度IALAMaritime课件
- 16版与03版《山东省建筑工程消耗量定额》对比与解读-建筑工程定额课件
- 四川方言词典(教你说一口地道的四川话)
- 企业标准编写模板
- 家具厂安全生产操作规程大全
- 提高卧床患者踝泵运动的执行率品管圈汇报书模板课件
- (推荐精选)PPI药理学基础与合理用药
评论
0/150
提交评论