您好,登錄后才能下訂單哦!
詳解Java使用super和this來(lái)重載構(gòu)造方法
實(shí)例代碼:
//父類 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; } //第一個(gè)構(gòu)造方法 public anotherPerson (String name){ this.name = name; } //第二個(gè)構(gòu)造方法 public anotherPerson(String name, String age){ this(name);//是用同一類中的其他構(gòu)造方法 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); } //第一個(gè)構(gòu)造方法 public Teacher(String age,String school){ super("babyDuncan",age);//使用父類的構(gòu)造方法 this.school = school; } public Teacher(String name,String age,String school){ this(age,school);//使用同一類的構(gòu)造方法,而這一構(gòu)造方法使用父類的構(gòu)造方法 this.name = name; } //重寫了父類的函數(shù) public void ShowInfomation(){ System.out.println("name is "+ name +" and age is "+age+" and school is "+school); } } public class testTeacher { /** * 測(cè)試一下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(); } }
輸出結(jié)果:
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的實(shí)例應(yīng)用,如有疑問(wèn)請(qǐng)留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。