詳解Java使用super和this來重載構(gòu)造方法
更新時間:2017年08月21日 11:10:30 投稿:lqh
這篇文章主要介紹了詳解Java使用super和this來重載構(gòu)造方法的相關(guān)資料,這里提供實例來幫助大家理解這部分內(nèi)容,需要的朋友可以參考下
詳解Java使用super和this來重載構(gòu)造方法
實例代碼:
//父類
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òu)造方法
public anotherPerson (String name){
this.name = name;
}
//第二個構(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ò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的實例應(yīng)用,如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
Java利用MD5加鹽實現(xiàn)對密碼進(jìn)行加密處理
在開發(fā)的時候,有一些敏感信息是不能直接通過明白直接保存到數(shù)據(jù)庫的。最經(jīng)典的就是密碼了。如果直接把密碼以明文的形式入庫,不僅會泄露用戶的隱私,對系統(tǒng)也是極其的不厲。本文就來和大家介紹一下如何對密碼進(jìn)行加密處理,感興趣的可以了解一下2023-02-02
SpringBoot快速構(gòu)建應(yīng)用程序方法介紹
這篇文章主要介紹了SpringBoot快速構(gòu)建應(yīng)用程序方法介紹,涉及SpringBoot默認(rèn)的錯誤頁面,嵌入式Web容器層面的約定和定制等相關(guān)內(nèi)容,具有一定借鑒價值,需要的朋友可以參考下。2017-11-11

