您好,登錄后才能下訂單哦!
詳解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的實例應用,如有疑問請留言或者到本站社區交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。