欢迎来到天天文库
浏览记录
ID:34659910
大小:174.62 KB
页数:14页
时间:2019-03-08
《lecture6-part1_inheritance》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、Object‐OrientedProgrammingLecture6Part1:InheritanceDr.LouisTangUnitedInternationalCollegeFall2010Outline•ClassInheritance•Keyword:extend•Overridemethod•Keyword:super•Keyword:final•ObjectClass•toStringandequalsIntroductiontoInheritance•Inheritanceisoneofthemaintechniq
2、uesofobject‐orientedprogramming(OOP)•Usingthistechnique,averygeneralformofaclassisfirstdefinedandcompiled,andthenmorespecializedversionsoftheclassaredefinedbyaddinginstancevariablesandmethods–Thespecializedclassesaresaidtoinheritthemethodsandinstancevariablesofthegen
3、eralclassIntroductiontoInheritance•Inheritanceistheprocessbywhichanewclassiscreatedfromanotherclass–Thenewclassiscalledasubclassorderivedclass–Theoriginalclassiscalledthesuperclassorbaseclass•Asubclassautomaticallyhasalltheinstancevariablesandmethodsthatthesuperclass
4、has,anditcanhaveadditionalmethodsand/orinstancevariablesaswell•Inheritanceisespeciallyadvantageousbecauseitallowscodetobereused,withouthavingtocopyitintothedefinitionsofthesubclassesTestPerson.javaMemoryAnalysisstackheapPersonnameageStudentSchoolDatasegmentInheritanc
5、einUMLPerson#nameSuper#ageClass+getName()+setName()+getAge()+setAge()InheritancerelationshipStudent-schoolSubClass+getSchool()+setSchool()+toString()+equals()Example:DerivedPersonClasses•Creatingasubclassisactuallyquitesimple.Atthebeginningofyourclassdeclaration,uset
6、heextendskeyword,followedbythenameoftheclasstoinheritfrom:classStudentextendsPerson{//newfieldsandmethodsdefiningastudentgohere}•ThisgivesStudentallthesamefieldsandmethodsasPerson,yetallowsitscodetofocusexclusivelyonthefeaturesthatmakeitunique.SubClasses•Whenasubclas
7、sisdefined,itissaidtoinherittheinstancevariablesandmethodsofthesuperclassthatitextends–ClassStudentdefinestheinstancevariablesschoolinitsclassdefinition•JustasitinheritstheinstancevariablesoftheclassPerson,theclassStudentinheritsallofitsmethodsaswell–TheclassStudenti
8、nheritsthemethodssetName,getName,setAge,andgetAgefromtheclassPerson–AnyobjectoftheclassStudentcanuseoneofthesemethods.–Studenthastw
此文档下载收益归作者所有
点击更多查看相关文章~~