当前位置: 移动技术网 > IT编程>开发语言>Java > 详解Java使用super和this来重载构造方法

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

2019年07月19日  | 移动技术网IT编程  | 我要评论

详解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

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网