Java 中 super 關鍵字的用途是什麼?


Java 中的super關鍵字是對父類/超類物件的引用。使用它,您可以引用/呼叫直接超類的欄位、方法或建構函式。

使用 super 關鍵字引用欄位

如上所述,您可以使用“super”關鍵字從子類的例項方法或建構函式中引用直接超類的例項欄位/變數。

如果一個類擴充套件了另一個類,則父類的成員副本將被建立在子類中,即使用子類的物件,您可以訪問子類和超類的成員。

如果一個類具有與超類變數名稱相同的變數,則可以使用 super 關鍵字區分超類變數和子類變數。

示例

在下面的 Java 示例中,我們有兩個類SuperClassSubClass,其中SubClass擴充套件了SuperClass,並且兩者都具有相同的變數“name”

SubClass類(display())的方法中,我們分別使用“super”“this”關鍵字列印兩個類的例項變數(name)的值。

線上演示

class SuperClass{
   String name = "Raju";
   public void display() {
      System.out.println("This is a method of the superclass");
   }
}
public class SubClass extends SuperClass{
   String name = "Ramu";
   public void display() {
      System.out.println("This is a method of the superclass");
      System.out.println("Value of name in superclass: "+super.name);
      System.out.println("Value of name in subclass: "+this.name);
   }
   public static void main(String args[]) {
      new SubClass().display();
   }
}

輸出

This is a method of the superclass
Value of name in superclass: Raju
Value of name in subclass: Ramu

使用 super 關鍵字引用超類建構函式

您還可以使用“super”關鍵字(顯式)從子類/子類的建構函式中引用/呼叫超類的建構函式。

示例

在下面的 Java 示例中,我們有兩個類 SuperClass 和 SubClass。在這裡,SubClass 擴充套件了 SuperClass,並且這兩個類都具有預設建構函式。我們嘗試使用super關鍵字從子類的建構函式中呼叫超類的建構函式。

線上演示

class SuperClass{
   String name = "Raju";
   public SuperClass() {
      System.out.println("This is the constructor of the superclass");
   }
}
public class SubClass extends SuperClass{
   String name = "Ramu";
   public SubClass() {
      System.out.println("This is a constructor of the subclass");
   }
   public static void main(String args[]) {
      new SubClass();
   }
}

輸出

This is the constructor of the superclass
This is a constructor of the subclass

使用 this 關鍵字呼叫方法

您還可以使用this從子類的例項方法中呼叫超類的(例項)方法。

示例

在下面的 Java 示例中,我們有兩個類 SuperClass 和 SubClass。在這裡,SubClass 擴充套件了 SuperClass。

在這裡,我們嘗試使用super關鍵字從子類名為 show 的方法中呼叫超類的display()方法。

線上演示

class SuperClass{
   String name = "Raju";
   public void display() {
      System.out.println("This is a method of the superclass");
   }
}
public class SubClass extends SuperClass{
   String name = "Ramu";
   public void show() {
      System.out.println("This is a method of the subclass");
      super.display();
   }
   public static void main(String args[]) {
      new SubClass().show();
   }
}

輸出

This is the constructor of the superclass
This is a constructor of the subclass

更新於: 2020-06-29

926 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.