Java中不同包的重寫方法


已測試

重寫的優勢在於能夠定義特定於子類型別的行為,這意味著子類可以根據其需求實現父類方法。

在面向物件術語中,重寫意味著重寫現有方法的功能。

示例

 線上演示

class Animal {
   public void move() {
      System.out.println("Animals can move");
   }
}
class Dog extends Animal {
   public void move() {
      System.out.println("Dogs can walk and run");
   }
}
public class TestDog {
   public static void main(String args[]) {
      Animal a = new Animal(); // Animal reference and object
      Animal b = new Dog(); // Animal reference but Dog object
      a.move(); // runs the method in Animal class
      b.move(); // runs the method in Dog class
   }
}

輸出

Animals can move
Dogs can walk and run

在上面的示例中,您可以看到,即使**b**是Animal型別,它也執行Dog類中的move方法。原因是:在編譯時,檢查是在引用型別上進行的。但是,在執行時,JVM會確定物件型別,並執行屬於該特定物件的方法。

因此,在上面的示例中,程式將正確編譯,因為Animal類具有move方法。然後,在執行時,它執行特定於該物件的方法。

示例

 線上演示

class Animal {
   public void move() {
      System.out.println("Animals can move");
   }
}
class Dog extends Animal {
   public void move() {
      System.out.println("Dogs can walk and run");
   }
public void bark() {
      System.out.println("Dogs can bark");
   }
}
public class TestDog {
   public static void main(String args[]) {
      Animal a = new Animal(); // Animal reference and object
      Animal b = new Dog(); // Animal reference but Dog object
      a.move(); // runs the method in Animal class
      b.move(); // runs the method in Dog class
      b.bark();
   }
}

輸出

TestDog.java:26: error: cannot find symbol
b.bark();
^
symbol: method bark()
location: variable b of type Animal
1 error

此程式將丟擲編譯時錯誤,因為b的引用型別Animal沒有名為bark的方法。

方法重寫的規則

  • 引數列表必須與被重寫方法的引數列表完全相同。

  • 返回型別應與超類中原始被重寫方法中宣告的返回型別相同或為其子型別。

  • 訪問級別不能比被重寫方法的訪問級別更嚴格。例如:如果超類方法宣告為public,那麼子類中的重寫方法不能是private或protected。

  • 例項方法只有在被子類繼承時才能被重寫。

  • 宣告為final的方法不能被重寫。

  • 宣告為static的方法不能被重寫,但可以被重新宣告。

  • 如果方法不能被繼承,則不能被重寫。

  • 與例項的超類位於同一包中的子類可以重寫任何未宣告為private或final的超類方法。

  • 不同包中的子類只能重寫宣告為public或protected的非final方法。

  • 重寫方法可以丟擲任何未檢查異常,無論被重寫方法是否丟擲異常。但是,重寫方法不應丟擲比被重寫方法宣告的異常更新或更廣泛的已檢查異常。重寫方法可以丟擲比被重寫方法更窄或更少的異常。

  • 建構函式不能被重寫。

使用super關鍵字

呼叫被重寫方法的超類版本時,使用**super**關鍵字。

示例

 線上演示

class Animal {
   public void move() {
      System.out.println("Animals can move");
   }
}
class Dog extends Animal {
   public void move() {
      super.move(); // invokes the super class method
      System.out.println("Dogs can walk and run");
   }
}
public class TestDog {
   public static void main(String args[]) {
      Animal b = new Dog(); // Animal reference but Dog object
      b.move(); // runs the method in Dog class
   }
}

輸出

Animals can move
Dogs can walk and run

測試

更新於:2020年6月26日

1K+ 瀏覽量

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告