Java中super關鍵字詳解
阿新 • • 發佈:2018-12-30
在Java的基礎學習中,慢慢接觸到許多陌生的關鍵字,今天來講一下我所認識的super關鍵字
它的使用場景為:有繼承在⭐(必須在繼承下才能使用super)
一.super呼叫(父類)構造方法
看下面這段程式碼
class Person{ public Person(){ System.out.println("1.Person類的構造方法"); } } class Student extends Person{ public Student(){ super(); //可寫可不寫,不寫系統會自動在子類無參構造前加上super();表示先呼叫父類的無參構造; System.out.println("2.Student類的構造方法"); } } public class Day6{ public static void main(String[] args){ Student stu = new Student(); } }
列印結果為:
1.Person類的構造方法
2.Student類的構造方法
注意:
1.當父類存在無參構造時,當呼叫子類無參構造時,系統會自動在子類無參構造前加上super(),表示先呼叫父類的無參構造。 super語句可以省略,此時子類可以使用this呼叫構造方法。
2.當父類不存在無參構造時(指父類一個無參構造方法都沒),必須在子類構造方法中使用super(引數);
明確指定呼叫父類的哪個有參構造。此時super語句不能省略;⭐且此時子類不存在this呼叫構造方法。
看下面這段程式碼:
class Person{ private String name; private int age; public Person(String name){ this.name = name; } public Person(String name, int age){ this(name); //this呼叫構造方法必須放在第一行,這裡這樣寫是為了避免程式碼重複 this.age = age; } public Person(){ System.out.println("1.Person類的構造方法"); } } class Student extends Person{ private String school; public Student(){ super("yy"); System.out.println("Student類的構造方法"); } public Student(String school){ this(); //super("yy"); //對super的呼叫必須在構造方法的第一行 System.out.println("2.Student類的構造方法"); } } public class Day6{ public static void main(String[] args){ Student stu = new Student("beida"); } }
執行結果如下:
Student類的構造方法
2.Student類的構造方法
這個程式碼中父類含有無參構造方法,所以在子類中可以使用this關鍵字來呼叫子類的構造方法,此時得省去super語句,免得跟this衝突,但省去後系統依舊會幫你加上,但不會報錯,若不省去則會報錯 ;
若將上面程式碼改成如下:
class Person{ private String name; private int age; public Person(String name){ this.name = name; } public Person(String name, int age){ this(name); //this呼叫構造方法必須放在第一行,這裡這樣寫是為了避免程式碼重複 this.age = age; } } class Student extends Person{ private String school; public Student(){ super("yy"); System.out.println("Student類的構造方法"); } public Student(String school){ this(); super("yy"); System.out.println("2.Student類的構造方法"); } } public class Day6{ public static void main(String[] args){ Student stu = new Student("beida"); } }
可見父類中沒有無參構造方法,但子類卻使用了this呼叫構造方法,這是不允許的,所以會報錯;
二.super呼叫普通方法
super呼叫方法或屬性都是指呼叫父類中的方法或屬性;
看下面簡單的應用:
class Person{
public String info = "father";
public void print(){
System.out.println("i am father");
}
}
class Student extends Person{
public Student(){
super.print();
System.out.println(super.info); //不能super.父類的私有屬性
}
}
public class Exer{
public static void main(String[] args){
Student stu = new Student();
}
}
將會輸出:
i am father
father
我們可以看到,其實super的使用方法和this關鍵字有很大的相似之處,但最大的區別就在於super是訪問父類的操作,而this是訪問本類的操作!!