资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

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


分享名称:详解Java使用super和this来重载构造方法
网站地址:http://cdkjz.cn/article/jedgsd.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220