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("小明同學");
    }
}

得到結果如下:
在這里插入圖片描述
在這里插入圖片描述
如果需要使用super(); 則super();必須放在第一行

super注意點

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

與this對比:
this :本身調用者這個對象
super: 代表父類對象的應用

前提:
this:沒有繼承也可以使用
super: 只能在繼承條件才可以使用

構造方法:
this (): 本類的構造
super(): 父類的構造


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM