Java Varargs中的方法重载和歧义

在Java中使用变量参数时存在歧义。发生这种情况是因为两种方法绝对可以有效地被数据值调用。因此,编译器不知道该调用哪种方法。

示例

public class Demo {
   static void my_fun(double ... my_Val){
      System.out.print("fun(double ...): " + "Number of args: " + my_Val.length );
      for(double x : my_Val)
      System.out.print(x + " ");
      System.out.println();
   }
   static void my_fun(boolean ... my_Val){
      System.out.print("fun(boolean ...) " + "The number of arguments: " + my_Val.length);
      for(boolean x : my_Val)
      System.out.print(x + " ");
      System.out.println();
   }
   public static void main(String args[]){
      my_fun(11.56, 34.78, 99.09, 56.66);
      System.out.println("Function 1 has been successfully called");
      my_fun(true, false, true, false);
      System.out.println("Function 2 has been successfully called");
      my_fun();
      System.out.println("Function 3 has been successfully called");
   }
}

输出结果

Demo.java:23: error: reference to my_fun is ambiguous
my_fun();
^
both method my_fun(double...) in Demo and method my_fun(boolean...) in Demo match
1 error

名为Demo的类定义了一个名为“ my_fun”的函数,该函数采用可变数量的浮点值。使用“ for”循环将这些值打印在控制台上。此函数已重载,并且参数是数量变化的布尔值。输出通过“ for”循环显示在控制台上。

在主函数中,首先使用浮点ppoint值调用“ my_fun”,然后使用布尔值调用,然后再不使用任何参数。导致的异常显示在控制台上。