已阅读5页,还剩58页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1 2 2FundamentalsofObject OrientedProgramming 2 2 2FundamentalsofOOP 2 2 1DesigningClasses2 2 2TransformingEnglishSpecificationintoJava2 2 3LifecycleofObjects2 2 4TheHtmlPageClass2 2 5UsingClassDocumentation2 2 6TheAlgaeColonyClass 3 Objectsinrealworld ObjectsarefundamentalbuildingblocksofObject OrientedProgramming OOP Objectsintherealworld physicalobjectsatiCarnegie iCarnegieemployeesThecomputersbeingusedeverydayThecoffeemakerabstractobjectsatiCarnegie TheiCarnegietrademarkEachoftencoursesiCarnegiebusinessplan 4 Softwareobjectsinaprogram representssomereal worldobject encapsulatesdata state andthemechanisms behavior thatoperateonthedata 5 Softwareobjectsinaprogram behavior attribute 6 Attributes Values andState ThevaluesforallattributesoftheobjecttakencollectivelydefinethestateoftheobjectThecomputerstoresthesevaluesasdata Thestateofanobjectcanchangeovertime Forexample whencatfish1swimsright thevalueforitscolumnattributechanges andhencethecatfishobject sstatechanges 7 Attributes Values andState 8 Behaviors Operations andServices Anobjecthaveitsownbehaviors Anobjectcanperformcertainoperationsactondata Someoperationsasaservicetootherobjects 9 Class Aclassisdefinedas asoftwareconstructthatdefinesthedata state andmethods behavior ofthespecificconcreteobjectsthataresubsequentlyconstructedfromthatclass Classislikeatemplatethatshapesallitsobjectinstances Allobjectswillhavealltheattributesandbehaviorsdefinedintheclass Conversely anobjectcannothaveanydataorperformanyoperationthatisabsentinitsclassdefinition 10 Class Thetemplateisusedtocreateobjects Eachobjecthasitsownvalueforeachattribute 11 AccessSpecifiers publicmembers variablesandmethods arefreelyavailableforanyone suse protectedmembersarepublictosubclasses packageaccess privatetoothers Friendly membershavepackageaccess noaccessspecifierpublicwithinthecontainingpackageprivatememberscanbeaccessed used onlybythemethodsofthecontainingclass 12 protected protected访问控制符能被用于方法和成员变量 声明为protected的方法和成员变量能被同一个包里的所有类所访问 就像默认修饰符package一样 能被该类的子类所访问 子类可以和父类不在一个包中 这样 当你想让一个类中的某个方法或成员变量在包中都可见 而且其子类也能访问 子类有可能和父类不在同一个包中 但又不想让所有类都可以访问该类时 就可以用protected修饰符 可访问性 public protected package private 13 protected Asubclassinanotherpackagecanaccesstheprotectedmembersinthesuper classviaonlythereferencesofsubclassoritssubclasses Asubclassinthesamepackagedoesn thavethisrestriction Thisensuresthatclassesfromotherpackagesareaccessingonlythemembersthatarepartoftheirinheritancehierarchy 14 protectedexample Bird java packagebirdpack publicclassBird protectedintnFeathers 15 protectedexample Duck1 java packageduckpack importbirdpack Bird publicclassDuck1extendsBird publicvoidsetn intduck1n 在子类中直接访问父类中的protected变量nFeathers duck1n 16 protectedexample Duck2 java packageduckpack importbirdpack Bird publicclassDuck2extendsBird publicvoidconstruct intnewduck2 Duck2d2 newDuck2 在子类中通过子类的对象访问父类中的protected变量d2 nFeathers newduck2 17 protectedexample Duck3 java packageduckpack importbirdpack Bird publicclassDuck3extendsBird publicvoidconstruct intnewduck3 Birdb newBird 子类中用父类对象反而不能访问父类中的protected变量b nFeathers newduck3 18 protectedexample Swan java packageduckpack importbirdpack Bird publicclassSwanextendsBird publicvoidconstruct intswan Duck1d1 newDuck1 子类中用另外一个子类的对象也不能访问父类中的protected变量d1 nFeathers swan 19 package编译技巧 当编译含有包声明的源文件时 使用 d选项会带来很多方便 它能保证编译后的class文件存放在正确的目录路径下 我们可以把上述5个文件都放在protectedtest目录下 然后用 d选项去编译 javac d Bird javajavac d Duck1 java 其中 表示以当前目录创建包结构的目录层次 编译成功后 会在protectedtest下生成2个目录 birdpack和duckpack 里面是生成的class文件 20 编译结果 编译上述几个文件 后2个不能通过 编译器提示 nFeathershasprotectedaccessinbirdpack Bird 总结 第4点说明 就算在子类中 也只能通过子类 或子类的子类 的引用来访问父类中的protected方法和成员变量 在Duck3和Swan两个子类中 直接通过父类和另一个子类来访问父类中的protected方法和成员变量就不行 21 22 Objectstate Thevaluesofallaspectsofanobjectconstituteitsstate Thebehaviorsofanobject ifproperlywritten willensurethatthestateofanobjectisalwaysconsistent Thisiscalledstateconsistency Forexample aproperlyoperatingcarshouldneverturnthetiresleftwhenthesteeringwheelturnsright 23 Hide 24 classandinstanceattribute intisadatatype 3isavalue orinstance ofthattypeAclassisadatatype anobjectisavalue instance ofthattypeAattributevalueiscommontoallinstancesofaclassAclassattributebelongstotheclassThereisonlyoneofit Thekeywordstaticmarksavariableasaclassvariable Aninstanceattributebelongstoindividualobjectsthereisoneofitforeachobject 25 Exampleofinstanceattribute publicclassJustAdd intx inty intz publicstaticvoidmain Stringargs JustAddmyself newJustAdd myself x 5 myself y 10 myself z myself x myself y 26 Exampleofstaticattribute classPerson Stringname Instancevariablebooleanalive Instancevariablestaticintpopulation ClassvariablePerson Stringname Constructorthis name name alive true population publicvoiddie Methodalive false population 27 classandinstancemethods Aninstancemethod belongsto anindividualobject Example saddamHussein die Aclass static methodbelongstoaclass Examples y Math abs x if Character isLetter ch 28 静态成员使用 注意 静态方法中只能使用其它静态变量或者静态方法 不能调用非静态变量或者方法静态方法中 如果定义了类的对象 则该对象既可以使用其它静态变量或者静态方法 也可以使用非静态变量或者方法静态方法不能被重写 即子类中不能有相同名称和参数的方法 29 静态成员 示例 publicclasstest staticintx 0 inty 0 publicstaticvoidmain Stringargs x 5 y 10 testmyself newtest myself x 15 myself y 20 testmyself2 newtest myself2 x 30 myself2 y 40 30 Callstaticvariableandmethod classStaticTest staticinti 47 classStaticFun staticvoidincr StaticTest i StaticTestst1 newStaticTest StaticTestst2 newStaticTest StaticFunsf newStaticFun Question st1 i st2 iorStaticTest iQuestion sf incr orStaticFun incr 31 Staticmainmethod Anapplicationrequiresapublicstaticvoidmain String args method Itmustbestaticbecause beforeyourprogramstarts therearen tanyobjectstosendmessagesto publicstaticvoidmain String args 32 Constants Therearesomeattributesforwhichthevaluedoesnotchangeonceitisset Justasanobjectcanhaveconstantattributes aclasscanalsohaveconstantattributes Thefinalkeywordmarksavariable invariant Example privatestaticfinalintBABY MIN ENERGY 5 33 DesigningaClass Identifyalltheobjectattributesandbehaviors Toidentifyattributes lookforadjectivesandpossessivephrases theXofY and Y sX inthesystemspecification numberoftheaccount and client sname Usually verbsarenotattributes Toidentifybehaviors lookforverbs Thestatement theclientdepositsmoneyintotheaccount indicatestheexistenceofthebehavior deposit 34 DesignProcessExample BankTeller 35 DesignProcessExample BankTeller 36 DesignProcessExample BankTeller Tolettheusercreateaccounts Tolettheuserselectanaccount Tolettheuserdepositorwithdrawmoney Tolettheusercheckthebalanceonaccounts 37 DecomposingtheProblem Whatarethecomponentsofthissystem TheGraphicalUserInterface GUI TheGUIcontrolsalluserinteractionsandcontainsallthatweseeonthescreen includingthetextfields theradioboxes andtheexecutebutton BankAccountKeepingtrackofthebalance handlingwithdrawals handlingdeposits andprovidingthebalancewhenaskedAccountsLedgerobjectsMaintainingacollectionofaccounts creatinganddeletingaccountswhenasked andlookingupaccounts 38 DecomposingtheProblem Whatarethecomponentsofthissystem TheGraphicalUserInterface TellerApplet java Modelsabankaccount BankAccount java Modelsaledger AccountsLedger java GUIactsasanintermediarybetweentheuserandourBankAccountandAccountsLedgerobjects GUIutilizestheservicesofBankAccountobjectstowithdrawanddepositmoney GUIutilizestheservicesofAccountsLedgerobjecttolookupspecificaccounts andtocreateanddeleteaccounts 39 DecomposingtheProblem Whatarethecomponentsofthissystem TheGraphicalUserInterface TellerApplet java Controlsalluserinteractions Containsallthatweseeonthescreen thetextfields theradioboxes theexecutebutton 40 DecomposingtheProblem Whatarethecomponentsofthissystem Modelsabankaccount BankAccount java Keepingtrackofthebalance Handlingwithdrawals Handlingdeposits Providingthebalancewhenasked 41 DecomposingtheProblem Whatarethecomponentsofthissystem Modelsaledger AccountsLedger java Maintainingacollectionofaccounts Creatinganddeletingaccountswhenasked Lookingupaccounts 42 Identifythebehaviorsofobjectinstances Whatservicesdoobjectinstancesofthisclassprovide Deposit Depositaspecifiedamountofmoney anintegernumber intotheaccount Increasethebalancebythespecifiedamount Public 43 Identifythebehaviorsofobjectinstances Whatservicesdoobjectinstancesofthisclassprovide Withdraw Withdrawaspecifiedamountofmoney anintegernumber fromthebalance Decreasethebalancebythespecifiedamount Public 44 Identifythebehaviorsofobjectinstances Whatservicesdoobjectinstancesofthisclassprovide getBalance inquiry Returnthecurrentbalanceoftheaccount Public 45 Identifythebehaviorsofobjectinstances Whatservicesdoobjectinstancesofthisclassprovide Constructor CreateandinitializeanaccountforthepersonwhosenameisspecifiedasaString Setthebeginningbalancetozero Setthebeginningbalancetozero Public 46 Identifytheattributesofobjectinstances Whatstateshouldinstancesofthisclassmaintain balance thetotalamountofmoneyintheaccountrepresentedasanintegernumberofdollars notaconstant aninstanceattribute private 47 Identifytheattributesofobjectinstances Whatstateshouldinstancesofthisclassmaintain Name thenameoftheaccount astringofcharacters aconstant aninstanceattribute public 48 DesigningtheBankAccountClass IdentifytheclassattributesofBankAccount minimumbalance 49 TheCompleteSpecificationfortheBankAccountClassBehaviors Constructor Createanaccountforthepersondeposit Increasethebalanceoftheaccountwithdraw DecreasethebalanceoftheaccountgetBalance inquiry ReturnthecurrentbalanceoftheaccountAttributes balance thetotalamountofmoneyintheaccountrepresentedasanintegername thecustomernameacharacterstring 50 TheCompleteSpecificationfortheAccountsLedgerClassBehaviors Constructor CreateanewAccountsLedgerobjecttheaccountsisinitializedtoanemptycollectionaddAccount CreateanewBankAccountobjectforacustomerwhosenameisspecifiedthenameisaStringpublicdeleteAccount Deleteacustomer sbankaccountforacustomerwhosenameisspecifiedthenameisaStringpubliclookupAccount LookupabankaccountbycustomernamethenameisaStringreturnamatchingBankAccountobjectpublicAttributes accounts AcollectionofBankAccountsaVectorprivate 51 Studentactivity PhoneBookTheabilitytoidentifythepropertiesandbehaviorsTheabilitytoidentifytheappropriateaccessibilitycriteria privateorpublic TheabilitytodistinguishbetweenobjectattributesandclassattributesTheabilitytoidentifyconstantsYoucanseetheimplementationinPhoneBook 52 53 2 2FundamentalsofOOP 2 2 1DesigningClasses2 2 2TransformingEnglishSpecificationintoJava2 2 3LifecycleofObjects2 2 4TheHtmlPageClass2 2 5UsingClassDocumentation2 2 6TheAlgaeColonyClass 54 MappingEnglishTermstoJavaTerms 55 BankAccountclassdiagram BankAccount java 56 JavaRulesandConventions ClassName Variables Constructor MethodNames ParameterSpecification ReturnValuesStudentactivity Contact 57 JavaRulesandConventions 1 ClassNameJava srulesstatethatanamecannotcontainaspace AccordingtoJavaconventions classnamesshouldbenouns Accordingtoconvention eachwordinthenameshouldstartwithanuppercaseletter Therestofthelettersarelowercase 58 JavaRulesandConvention
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025年绿色建筑材料研究与开发可行性研究报告及总结分析
- 2025年线上健身服务平台开发项目可行性研究报告及总结分析
- 2023年医师三基三严理论知识模拟复习试题及答案二
- 2025年企业团建活动场地合同
- 2020-2025年中级银行从业资格之中级银行管理押题练习试卷A卷附答案
- 2020-2025年监理工程师之土木建筑监理案例分析题库综合试卷A卷附答案
- 2025年山西长治市襄垣县保安员招聘考试题库附答案解析
- 2025年绿色食品研发项目可行性研究报告及总结分析
- 2025年农业项目开发合同协议
- 2025年垃圾分类管理系统研究项目可行性研究报告及总结分析
- 小儿推拿在儿童肺部疾病中的应用
- 部编版四年级上册语文提分计划
- 呼吸科进修汇报护理
- 2025年上海市中考数学试卷真题(含答案解析)
- 妇科围手术期患者的护理
- 《广告文案写作教程(第四版)》课件 第五章
- DB62T 3253-2023 建筑与市政基础设施工程勘察文件编制技术标准
- 吸塑托盘采购合同协议
- 2025年度消防设备维修合同:消防水炮维修与安装服务协议
- 2025年四川凉山州卫生健康委员会考调所属事业单位工作人员2人历年高频重点提升(共500题)附带答案详解
- 2024年度房屋建筑工程施工合同终止协议书模板3篇
评论
0/150
提交评论