Java 中的方法隱藏和方法重寫有什麼區別?


當超類和子類包含相同例項方法(包括引數)時,呼叫時,超類方法會由子類的方法覆蓋。

在這個示例中,超類和子類具有簽名相同的(方法名和引數)方法,當我們嘗試從子類呼叫此方法時,子類方法覆蓋超類的方法並得到執行。

示例

即時演示

class Super{
   public void sample(){
      System.out.println("Method of the Super class");
   }
}
public class MethodOverriding extends Super {
   public void sample(){
      System.out.println("Method of the Sub class");
   }
   public static void main(String args[]){
      MethodOverriding obj = new MethodOverriding();
      obj.sample();
   }
}

輸出

Method of the Sub class

當超類和子類包含相同的方法(包括引數),且它們是靜態的,並且在呼叫時,超類方法將被子類的方法隱藏。

示例

即時演示

class Super{
   public static void sample(){
      System.out.println("Method of the Super class");
   }
}
public class MethodHiding extends Super {
   public static void sample(){
      System.out.println("Method of the Sub class");
   }
   public static void main(String args[]){
      MethodHiding obj = new MethodHiding();
      obj.sample();
   }
}

輸出

Method of the Sub class

更新於: 2019 年 7 月 30 日

2000+ 瀏覽量

開啟你的 職業生涯

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.