Java 中方法過載有哪些限制?


當一個類有兩個或多個名稱相同但引數不同的方法時,在呼叫時,根據傳遞的引數呼叫相應的方法(或相應的方法體將動態地繫結到呼叫行)。這種機制被稱為**方法過載**。

示例

 線上演示

class Test{
   public int division(int a, int b){
      int result = a/b;
      return result;
   }
   public double division (float a, float b){
      double result = a/b;
      return result;
   }
}
public class OverloadingExample{
   public static void main(String args[]){
      Test obj = new Test();
      System.out.println("division of integers: "+obj.division(100, 40));
      System.out.println("division of floating point numbers: "+obj.division(214.225f, 50.60f));
   }
}

輸出

division of integers: 2
division of floating point numbers: 4.233695983886719

方法過載需要遵循的規則

在過載時,您需要牢記以下幾點:

  • 兩種方法都應該在同一個類中。
  • 方法的名稱應該相同,但它們應該具有不同的引數數量或型別。

如果名稱不同,它們將成為不同的方法,如果它們具有相同的名稱和引數,則會丟擲編譯時錯誤,提示“方法已定義”。

示例

class Test{
   public int division(int a, int b){
      int result = a/b;
      return result;
   }
   public double division (int a, int b){
      double result = a/b;
      return result;
   }
}

編譯時錯誤

OverloadingExample.java:6: error: method division(int, int) is already defined in class Test
public static double division (int a, int b){
                     ^
1 error

在重寫中,如果兩種方法都遵循以上兩條規則,則它們可以:

  • 具有不同的返回型別。

示例

class Test{
   public int division(int a, int b){
      int result = a/b;
      return result;
   }
   public void division (float a, float b){
      double result = a/b;
      System.out.println("division of floating point numbers: "+result);
   }
}
  • 具有不同的訪問修飾符:
class Test{
   public int division(int a, int b){
      int result = a/b;
      return result;
   }
   private void division (float a, float b){
      double result = a/b;
      System.out.println("division of floating point numbers: "+result);
   }
}
  • 可以丟擲不同的異常:
class Test{
   public int division(int a, int b)throws FileNotFoundException{
      int result = a/b;
      return result;
   }
   private void division (float a, float b)throws Exception{
      double result = a/b;
      System.out.println("division of floating point numbers: "+result);
   }
}

更新於: 2019-07-30

855 次檢視

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.