Java 中可变参数的方法重载与歧义
在 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”循环将输出显示在控制台上。
在 main 函数中,首先使用浮点值调用“my_fun”,然后使用布尔值调用,然后在没有任何参数的情况下调用。它导致的异常将显示在控制台上。
广告