详解Java使用super和this来重载构造方法

网友投稿 220 2023-04-17


详解Java使用super和this来重载构造方法

详解java使用super和this来重载构造方法

实例代码:

//父类

class anotherPerson{

String name = "";

String age = "";

public String getAge() {

return age;

}

public void setAge(String age) {

this.age = age;

}

public void setName(String name){

this.name = name;

}

public String getName(){

return name;

}

//第一个构造方法

public anotherPerson (String name){

this.name = name;

}

//第二个构造方法

public anotherPerson(String name, String age){

this(name);//是用同一类中的其他构造方法

this.age = age;

}

public void ShowInfomation(){

System.out.println("name is "+ name +"and age is "+age);

}

}

//子类

class Teacher extends anotherPerson{

String school = "";

public void setSchool(String school){

this.school = school;

}

public String getSchool(){

return school;

}

public Teacher(String name){

super(name);

}

//第一个构造方法

public Teacher(String age,String school){

super("babyDuncan",age);//使用父类的构造方法

this.school = school;

}

public Teacher(String name,String age,String school){

this(age,school);//使用同一类的构造方法,而这一构造方法使用父类的构造方法

this.name = name;

}

//重写了父类的函数

public void ShowInfomation(){

System.out.println("name is "+ name +" and age is "+age+" and school is "+school);

}

}

public class testTeacher {

/**

* 测试一下super和this

*/

public static void main(String[] args) {

// TODO Auto-generated method stub

anotherPerson person1 = new anotherPerson("babyDuncan");

anotherPerson person2 = new anotherPerson("babyDuncan","20");

Teacher teacher1 = new Teacher("babyDuncan");

Teacher teacher2 = new Teacher("20","JLU");

Teacher teacher3 = new Teacher("babyDuncan","20","JLU");

person1.ShowInfomation();

person2.ShowInfomation();

teacher1.ShowInfomatiUvRRoJLyfon();

teacher2.ShowInfomation();

teacher3.ShowInfomation();

}

}

输出结果:

name is babyDuncanand age is

name is babyDuncanand age is 20

name is babyDuncan and age is and school ishttp://

name is babyDuncan and age is 20 and school is JLU

name is babyDuncan and age is 20 and school is JLU

以上就是java this与super的实例应用,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:关于python dubbo接口测试工具的信息
下一篇:接口测试自动化框架特点(自动化接口测试框架搭建)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~