Java 中 super() 與 this() 的區別


以下列出了 Java 中 super() 方法與 this() 方法之間的顯著區別。

 super()this()
定義super() - 指代直接父類的例項。this() - 指代當前類例項。
呼叫可用於呼叫直接父類的成員方法。可用於呼叫當前類的成員方法。
建構函式super() 用作直接父類的建構函式,並且應為子類建構函式中的第一行。this() 用作當前類的建構函式,並可在帶引數的建構函式中使用。
重寫當呼叫某個被重寫方法的超類版本時,應使用 super 關鍵字。當呼叫某個被重寫方法的當前版本時,應使用 this 關鍵字。

示例

 即時演示

class Animal {
   String name;
   Animal(String name) {
      this.name = name;
   }
   public void move() {
      System.out.println("Animals can move");
   }
   public void show() {
      System.out.println(name);
   }
}
class Dog extends Animal {
   Dog() {
      //Using this to call current class constructor
      this("Test");
   }
   Dog(String name) {
      //Using super to invoke parent constructor
      super(name);
   }
   public void move() {
      // invokes the super class method
      super.move();
      System.out.println("Dogs can walk and run");
   }
}
public class Tester {
   public static void main(String args[]) {
      // Animal reference but Dog object
      Animal b = new Dog("Tiger");
      b.show();
      // runs the method in Dog class
      b.move();
   }
}

輸出

Tiger
Animals can move
Dogs can walk and run

更新時間: 21-6-2020

6K+ 瀏覽

開啟您的事業

完成課程以取得認證

立即開始
廣告
© . All rights reserved.