詳解Java使用super和this來重載構(gòu)造方法
更新時(shí)間:2017年08月21日 11:10:30 投稿:lqh
這篇文章主要介紹了詳解Java使用super和this來重載構(gòu)造方法的相關(guān)資料,這里提供實(shí)例來幫助大家理解這部分內(nèi)容,需要的朋友可以參考下
詳解Java使用super和this來重載構(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 {
/**
* 測試一下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)用,如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
Java利用MD5加鹽實(shí)現(xiàn)對密碼進(jìn)行加密處理
在開發(fā)的時(shí)候,有一些敏感信息是不能直接通過明白直接保存到數(shù)據(jù)庫的。最經(jīng)典的就是密碼了。如果直接把密碼以明文的形式入庫,不僅會(huì)泄露用戶的隱私,對系統(tǒng)也是極其的不厲。本文就來和大家介紹一下如何對密碼進(jìn)行加密處理,感興趣的可以了解一下2023-02-02
SpringBoot快速構(gòu)建應(yīng)用程序方法介紹
這篇文章主要介紹了SpringBoot快速構(gòu)建應(yīng)用程序方法介紹,涉及SpringBoot默認(rèn)的錯(cuò)誤頁面,嵌入式Web容器層面的約定和定制等相關(guān)內(nèi)容,具有一定借鑒價(jià)值,需要的朋友可以參考下。2017-11-11
java實(shí)現(xiàn)學(xué)生選課系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)學(xué)生選課系統(tǒng),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-02-02
springboot+dubbo實(shí)現(xiàn)時(shí)間輪算法
時(shí)間輪是一種高效利用線程資源進(jìn)行批量化調(diào)度的算法,本文主要介紹了springboot+dubbo實(shí)現(xiàn)時(shí)間輪算法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
2025-04-04 
