欢迎来到天天文库
浏览记录
ID:22670228
大小:331.50 KB
页数:43页
时间:2018-10-21
《java程序员培训定制课程c06》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、第六章Java类设计本章内容Java类的继承方法的重载、重写多态性及其应用成员访问控制对象的创建和初始化细节几种常用的Java类2类的继承(1)为描述和处理个人信息,定义类Person:publicclassPerson{publicStringname;publicintage;publicDatebirthDate;publicStringgetInfo(){...}}Person+name:String+age:int+birthDate:Date+getInfo():String3类的继承(2)为描述和处理学生信息,定义类Student
2、:publicclassStudent{publicStringname;publicintage;publicDatebirthDate;publicStringschool;publicStringgetInfo(){...}}Student+name:String+age:int+birthDate:Date+school:String+getInfo():String4类的继承(3)通过继承,简化Student类的定义:publicclassPerson{publicStringname;publicintage;publicDateb
3、irthDate;publicStringgetInfo(){...}}publicclassStudentextendsPerson{publicStringschool;}Person+name:String+age:int+birthDate:Date+getInfo():StringStudent+school:String5类的继承(4)类继承语法规则:class[extends]{*}Object类是所有Java类的最高层父类Java只支持单继承,不
4、允许多重继承一个子类只能有一个父类一个父类可以继承出多个子类6单继承举例(1)Person+name:String+age:int+birthDate:Date+getInfo():StringStudent+school:StringSoldierOfficerGraduate+major:history+register():void7单继承举例(2)publicclassTestAnimals{publicstaticvoidmain(String[]args){Horseb=newHorse();System.out.println(b
5、.getI());}}classAnimal{privateinti=1;publicintgetI(){returni;}publicvoidsetI(inti){this.i=i;}}classHorseextendsAnimal{inti=2;}8访问控制ModiferSameClassSamePackageSubclassUniverseprivateYesdefaultYesYesprotectedYesYesYespublicYesYesYesYes可以对Java类中定义的属性和方法进行访问控制----规定不同的保护等级:9访问控制
6、举例(1)classParent{privateintf1=1;intf2=2;protectedintf3=3;publicintf4=4;privatevoidfm1(){System.out.println("infm1()f1="+f1);}voidfm2(){System.out.println("infm2()f2="+f2);}protectedvoidfm3(){System.out.println("infm3()f3="+f3);}publicvoidfm4(){System.out.println("infm4()f4="
7、+f4);}}10访问控制举例(2)classChildextendsParent{privateintc1=21;publicintc2=22;privatevoidcm1(){System.out.println("incm1()c1="+c1);}publicvoidcm2(){System.out.println("incm2()c2="+c2);}publicstaticvoidmain(Stringargs[]){inti;Parentp=newParent();i=p.f2;//i=p.f3;i=p.f4;p.fm2();//p.
8、fm3();p.fm4();Childc=newChild();i=c.f2;//i=c.f3;i=c.f4;i=c.c1;//i=c.c2;c.cm
此文档下载收益归作者所有