Java中的方法過載和方法隱藏有什麼區別?


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

示例

線上演示

class Demo{
   public static void demoMethod() {
      System.out.println("method of super class");
   }
}
public class Sample extends Demo{
   public static void demoMethod() {
      System.out.println("method of sub class");
   }
   public static void main(String args[] ){
      Sample.demoMethod();
   }
}

輸出

method of sub class

方法過載 − 當一個類包含兩個同名函式和不同引數時,在呼叫時,JVM 根據函式引數執行此方法,這稱為方法過載。

示例

線上演示

public class Sample{
   public static void add(int a, int b){
      System.out.println(a+b);
   }
   public static void add(int a, int b, int c){
      System.out.println(a+b+c);
   }
   public static void main(String args[]){
      Sample obj = new Sample();
      obj.add(20, 40);
      obj.add(40, 50, 60);
   }
}

輸出

60 
150

更新於: 2019 年 7 月 30 日

887 次瀏覽

開啟您的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.