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.ShowInfomation();
teacher2.ShowInfomation();
teacher3.ShowInfomation();
}

}


输出结果:
name is babyDuncanand age is
name is babyDuncanand age is 20
name is babyDuncan and age is and school is
name is babyDuncan and age is 20 and school is JLU
name is babyDuncan and age is 20 and school is JLU
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值