详解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的实例应用,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下