Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Nạp chồng phương thức và sự lưỡng nghĩa trong Varargs trong Java


Có sự lưỡng nghĩa khi dùng biến tham số (varargs) trong Java. Điều này xảy ra vì hai phương thức hoàn toàn có thể hợp lệ để được gọi bởi các giá trị dữ liệu. Do đó, trình biên dịch không biết gọi phương thức nào.

Ví dụ

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");    } }

Kết quả

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

Lớp Demo định nghĩa hàm my_fun nhận số lượng biến đổi giá trị float. Giá trị in ra bằng vòng lặp for. Hàm này được nạp chồng với tham số boolean biến đổi. Đầu ra hiển thị bằng for.

Trong main, my_fun gọi với giá trị float, sau đó boolean, sau đó không tham số. Ngoại lệ xảy ra hiển thị trên console.