欢迎来到天天文库
浏览记录
ID:30840779
大小:924.28 KB
页数:59页
时间:2019-01-04
《第一行代码java-源代码-第4章【课程代码】面向对象高级知识》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、第四章:面向对象高级知识4.1继承性范例4-1:要求定义两个描述人与学生的类。Person.java:Student.java:classPerson{classStudent{privateStringname;privateStringname;privateintage;privateintage;publicvoidsetName(Stringname){privateStringschool;this.name=name;publicvoidsetName(Stringname){}this.name=na
2、me;publicvoidsetAge(intage){}this.age=age;publicvoidsetAge(intage){}this.age=age;publicgetName(){1returnthis.name;publicvoidsetSchool(Stringschool){}this.school=school;publicintgetAge(){}returnthis.age;publicStringgetSchool(){}returnthis.school;}}publicStringge
3、tName(){returnthis.name;}publicintgetAge(){returnthis.age;}}范例4-2:继承的基本实现。classPerson{privateStringname;privateintage;publicvoidsetName(Stringname){this.name=name;}publicvoidsetAge(intage){this.age=age;}publicStringgetName(){returnthis.name;}publicintgetAge(){r
4、eturnthis.age;}}classStudentextendsPerson{//Student类继承了Person类//此类没有定义任何的操作方法}publicclassTestDemo{publicstaticvoidmain(Stringargs[J){Studentstu=newStudent();//实例化的是子类stu.setName("张三”);//Person类定义stu.setAge(20);//Person类定义System.oW.printlnC姓名:"+stu.getName()+H,年
5、龄:"+stu.getAge());}}范例4-3:在子类中扩充方法。classPerson{privateStringname;privateintage;publicvoidsetName(Stringname){this.name=name;}publicvoidsetAge(intage){this.age=age;}publicStringgetName(){returnthis.name;}publicintgetAge(){returnthis.age;}}classStudentextendsPers
6、on{privateStringschool;publicvoidsetSchool(Stringschool){this.school=school;}publicStringgetSchool(){returnthis.school;}}publicclassTestDemo{publicstaticvoidmain(StringargsQ){Studentstu=newStudent();//stu.setName("张三”);stu.setAge(20);//Student类继承了Person类//子类扩充的
7、属性//扩充的方法//扩充的方法实例化的是子类//Person类定义//Person类定义stu.setSchool(M清华大学");//Student类扩充方法System.outprintln(H姓名:M+stu.getName()+R,年龄:11+stu.getAge()+J学校:”+stu.getSchool());范例4-4:错误的继承。classA{}classB{}classCextendsA,B{}//—个子类继承了两个父类范例4-5:多层继承。classA0classBextendsA0classC
8、extendsB{}//B类继承A类//C类继承B类范例4-6:观察属性。classA{privateStringmsg;publicvoidsetMsg(Stringmsg){this.msg=msg;}publicStringgetMsg(){returnthis.msg;}}classBextendsA{//继承自A类}publiccla
此文档下载收益归作者所有