我可以在 Java 中過載 private(私有)方法嗎?


過載是實現多型性的一種機制,其中一個類包含兩個名稱相同、引數不同的方法。

每當您呼叫此方法時,方法都會根據引數與方法呼叫繫結。

過載 private(私有)方法

是的,我們可以在 Java 中過載 private(私有)方法,但只能在同一個類中訪問它們。

示例

 線上演示

public class Calculator {
   private int addition(int a , int b){
      int result = a+b;
      return result;
   }
   private int addition(int a , int b, int c){
      int result = a+b+c;
      return result;
   }
   public static void main(String args[]){
      Calculator obj = new Calculator();
      System.out.println(obj.addition(12, 13));
      System.out.println(obj.addition(12, 13, 15));
   }
}

輸出

25
40

更新時間: 2019 年 7 月 30 日

2K+ 次瀏覽

開啟您的職業生涯

完成課程並獲得認證

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