详解Java使用super和this来重载构造方法
详解Java使用super和this来重载构造方法
实例代码:
//父类
classanotherPerson{
Stringname="";
Stringage="";
publicStringgetAge(){
returnage;
}
publicvoidsetAge(Stringage){
this.age=age;
}
publicvoidsetName(Stringname){
this.name=name;
}
publicStringgetName(){
returnname;
}
//第一个构造方法
publicanotherPerson(Stringname){
this.name=name;
}
//第二个构造方法
publicanotherPerson(Stringname,Stringage){
this(name);//是用同一类中的其他构造方法
this.age=age;
}
publicvoidShowInfomation(){
System.out.println("nameis"+name+"andageis"+age);
}
}
//子类
classTeacherextendsanotherPerson{
Stringschool="";
publicvoidsetSchool(Stringschool){
this.school=school;
}
publicStringgetSchool(){
returnschool;
}
publicTeacher(Stringname){
super(name);
}
//第一个构造方法
publicTeacher(Stringage,Stringschool){
super("babyDuncan",age);//使用父类的构造方法
this.school=school;
}
publicTeacher(Stringname,Stringage,Stringschool){
this(age,school);//使用同一类的构造方法,而这一构造方法使用父类的构造方法
this.name=name;
}
//重写了父类的函数
publicvoidShowInfomation(){
System.out.println("nameis"+name+"andageis"+age+"andschoolis"+school);
}
}
publicclasstestTeacher{
/**
*测试一下super和this
*/
publicstaticvoidmain(String[]args){
//TODOAuto-generatedmethodstub
anotherPersonperson1=newanotherPerson("babyDuncan");
anotherPersonperson2=newanotherPerson("babyDuncan","20");
Teacherteacher1=newTeacher("babyDuncan");
Teacherteacher2=newTeacher("20","JLU");
Teacherteacher3=newTeacher("babyDuncan","20","JLU");
person1.ShowInfomation();
person2.ShowInfomation();
teacher1.ShowInfomation();
teacher2.ShowInfomation();
teacher3.ShowInfomation();
}
}
输出结果:
nameisbabyDuncanandageis nameisbabyDuncanandageis20 nameisbabyDuncanandageisandschoolis nameisbabyDuncanandageis20andschoolisJLU nameisbabyDuncanandageis20andschoolisJLU
以上就是javathis与super的实例应用,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!