java语言程序设计-基础篇-原书第八版-课件-PPT(第十七章).ppt
《java语言程序设计-基础篇-原书第八版-课件-PPT(第十七章).ppt》由会员分享,可在线阅读,更多相关《java语言程序设计-基础篇-原书第八版-课件-PPT(第十七章).ppt(62页珍藏版)》请在淘文阁 - 分享文档赚钱的网站上搜索。
1、Chapter8ObjectsandClasses1MotivationsAfterlearningtheprecedingchapters,youarecapableofsolvingmanyprogrammingproblemsusingselections,loops,methods,andarrays.However,theseJavafeaturesarenotsufficientfordevelopinggraphicaluserinterfacesandlargescalesoftwaresystems.Supposeyouwanttodevelopagraphicaluseri
2、nterfaceasshownbelow.Howdoyouprogramit?2ObjectivesFTodescribeobjectsandclasses,anduseclassestomodelobjects(8.2).FTouseUMLgraphicalnotationstodescribeclassesandobjects(8.2).FTodemonstratedefiningclassesandcreatingobjects(8.3).FTocreateobjectsusingconstructors(8.4).FToaccessobjectsviaobjectreferenceva
3、riables(8.5).FTodefineareferencevariableusingareferencetype(8.5.1).FToaccessanobjectsdataandmethodsusingtheobjectmemberaccessoperator(.)(8.5.2).FTodefinedatafieldsofreferencetypesandassigndefaultvaluesforanobjectsdatafields(8.5.3).FTodistinguishbetweenobjectreferencevariablesandprimitivedatatypevari
4、ables(8.5.4).FTouseclassesDate,Random,andJFrameintheJavalibrary(8.6).FTodistinguishbetweeninstanceandstaticvariablesandmethods(8.7).FTodefineprivatedatafieldswithappropriategetandsetmethods(8.8).FToencapsulatedatafieldstomakeclasseseasytomaintain(8.9).FTodevelopmethodswithobjectargumentsanddifferent
5、iatebetweenprimitive-typeargumentsandobject-typearguments(8.10).FTostoreandprocessobjectsinarrays(8.11).3OOProgrammingConceptsObject-orientedprogramming(OOP)involvesprogrammingusingobjects.Anobjectrepresentsanentityintherealworldthatcanbedistinctlyidentified.Forexample,astudent,adesk,acircle,abutton
6、,andevenaloancanallbeviewedasobjects.Anobjecthasauniqueidentity,state,andbehaviors.Thestateofanobjectconsistsofasetofdatafields(alsoknownasproperties)withtheircurrentvalues.Thebehaviorofanobjectisdefinedbyasetofmethods.4ObjectsAnobjecthasbothastateandbehavior.Thestatedefinestheobject,andthebehaviord
7、efineswhattheobjectdoes.5ClassesClassesareconstructsthatdefineobjectsofthesametype.AJavaclassusesvariablestodefinedatafieldsandmethodstodefinebehaviors.Additionally,aclassprovidesaspecialtypeofmethods,knownasconstructors,whichareinvokedtoconstructobjectsfromtheclass.6Classes7UMLClassDiagram8Example:
8、Defining Classes and Creating ObjectsFObjective:Demonstratecreatingobjects,accessingdata,andusingmethods.TestCircle1Run9Example:Defining Classes and Creating ObjectsFObjective:Demonstratecreatingobjects,accessingdata,andusingmethods.TestTVRunTV10ConstructorsCircle()Circle(double newRadius)radius=new
9、Radius;Constructorsareaspecialkindofmethodsthatareinvokedtoconstructobjects.11Constructors,cont.Aconstructorwithnoparametersisreferredtoasano-arg constructor.Constructorsmusthavethesamenameastheclassitself.Constructorsdonothaveareturntypenotevenvoid.Constructorsareinvokedusingthenewoperatorwhenanobj
10、ectiscreated.Constructorsplaytheroleofinitializingobjects.12CreatingObjectsUsingConstructorsnew ClassName();Example:new Circle();new Circle(5.0);13DefaultConstructorAclassmaybedeclaredwithoutconstructors.Inthiscase,ano-argconstructorwithanemptybodyisimplicitlydeclaredintheclass.Thisconstructor,calle
11、da default constructor,isprovidedautomaticallyonly if no constructors are explicitly declared in the class.14DeclaringObjectReferenceVariablesToreferenceanobject,assigntheobjecttoareferencevariable.Todeclareareferencevariable,usethesyntax:ClassName objectRefVar;Example:Circle myCircle;15Declaring/Cr
12、eatingObjectsinaSingleStepClassName objectRefVar=new ClassName();Example:Circle myCircle=new Circle();CreateanobjectAssignobjectreference16AccessingObjectsFReferencingtheobjectsdata:objectRefVar.data e.g.,myCircle.radiusFInvokingtheobjectsmethod:objectRefVar.methodName(arguments)e.g.,myCircle.getAre
13、a()17TraceCodeCirclemyCircle=newCircle(5.0);SCircleyourCircle=newCircle();yourCircle.radius=100;DeclaremyCirclenovaluemyCircleanimation18TraceCode,cont.CirclemyCircle=newCircle(5.0);CircleyourCircle=newCircle();yourCircle.radius=100;novaluemyCircleCreateacircleanimation19TraceCode,cont.CirclemyCircl
14、e=newCircle(5.0);CircleyourCircle=newCircle();yourCircle.radius=100;referencevaluemyCircleAssignobjectreferencetomyCircleanimation20TraceCode,cont.CirclemyCircle=newCircle(5.0);CircleyourCircle=newCircle();yourCircle.radius=100;referencevaluemyCirclenovalueyourCircleDeclareyourCircleanimation21Trace
15、Code,cont.CirclemyCircle=newCircle(5.0);CircleyourCircle=newCircle();yourCircle.radius=100;referencevaluemyCirclenovalueyourCircleCreateanewCircleobjectanimation22TraceCode,cont.CirclemyCircle=newCircle(5.0);CircleyourCircle=newCircle();yourCircle.radius=100;referencevaluemyCirclereferencevalueyourC
16、ircleAssignobjectreferencetoyourCircleanimation23TraceCode,cont.CirclemyCircle=newCircle(5.0);CircleyourCircle=newCircle();yourCircle.radius=100;referencevaluemyCirclereferencevalueyourCircleChangeradiusinyourCircleanimation24CautionRecallthatyouuseMath.methodName(arguments)(e.g.,Math.pow(3,2.5)toin
17、vokeamethodintheMathclass.CanyouinvokegetArea()usingCircle1.getArea()?Theanswerisno.Allthemethodsusedbeforethischapterarestaticmethods,whicharedefinedusingthestatickeyword.However,getArea()isnon-static.ItmustbeinvokedfromanobjectusingobjectRefVar.methodName(arguments)(e.g.,myCircle.getArea().Moreexp
18、lanationswillbegiveninthesectionon“StaticVariables,Constants,andMethods.”25ReferenceDataFieldsThedatafieldscanbeofreferencetypes.Forexample,thefollowingStudentclasscontainsadatafieldnameoftheStringtype.public class Student String name;/name has default value null int age;/age has default value 0 boo
19、lean isScienceMajor;/isScienceMajor has default value false char gender;/c has default value u000026ThenullValueIfadatafieldofareferencetypedoesnotreferenceanyobject,thedatafieldholdsaspecialliteralvalue,null.27DefaultValueforaDataFieldThedefaultvalueofadatafieldisnullforareferencetype,0foranumerict
20、ype,falseforabooleantype,andu0000forachartype.However,Javaassignsnodefaultvaluetoalocalvariableinsideamethod.public class Test public static void main(String args)Student student=new Student();System.out.println(name?+student.name);System.out.println(age?+student.age);System.out.println(isScienceMaj
21、or?+student.isScienceMajor);System.out.println(gender?+student.gender);28Examplepublic class Test public static void main(String args)int x;/x has no default value String y;/y has no default value System.out.println(x is +x);System.out.println(y is +y);Compilationerror:variablesnotinitializedJavaass
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- java 语言程序设计 基础 第八 课件 PPT 第十七
限制150内