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-Jun-2020

6K+ 瀏覽

啟動你的 職業生涯

完成課程以獲得認證

開始使用
廣告
© . All rights reserved.