欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-21 10:53:58
详解java使用super和this来重载构造方法 实例代码: //父类 class anotherperson{ string name = ""...

详解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的实例应用,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!