天天看點

java super詳解

super

super是一個關鍵字,super和this很類似,其文法是“super.”和“super()”,不能在靜态方法中使用。在子類對象中,子類想通路父類的東西,可以使用“super.”的方式通路。

代碼舉例

在Person(父類)中建立一個屬性name;

public class Person {
    protected  String name="小王同學";

}
           

在Student(子類)中建立一個屬性和一個方法print方法

public class Student extends Person {
    protected String name="小徐同學";

    public  void  print(String name){
        System.out.println(name);//輸出的是方法裡面的參數
        System.out.println(this.name);//輸出的是屬性裡面的name
        System.out.println(super.name);//輸出的是父類Person類裡面的屬性name
    }
}
           

在Test(主類)中調用Student中的方法,并指派

public class Test {
    public static void main(String[] args) {
        Student xingming = new Student();
        xingming.print("小明同學");
    }
}
           

得到結果如下:

java super詳解
java super詳解

如果需要使用super(); 則super();必須放在第一行

super注意點

  1. super 調用父類的構造方法,必須在構造方法的第一個。
  2. super必須隻能出現在子類的方法或者構造方法中
  3. super和this不能同時調用構造方法。

與this對比:

this :本身調用者這個對象

super: 代表父類對象的應用

前提:

this:沒有繼承也可以使用

super: 隻能在繼承條件才可以使用

構造方法:

this (): 本類的構造

super(): 父類的構造

上一篇: java繼承