Wednesday, January 9, 2019

Sometimes unexpected errors can result when overloading a method that takes a variable length argument?


// Java program to illustrate Varargs and ambiguity
class Test
{
    // A method that takes varargs(here integers).
    static void fun(int ... a)
    {
        System.out.print("fun(int ...): " +
                "Number of args: " + a.length +
                " Contents: ");
       
        // using for each loop to display contents of a
        for(int x : a)
            System.out.print(x + " ");
       
        System.out.println();
    }
   
    // A method that takes varargs(here booleans).
    static void fun(boolean ... a)
    {
        System.out.print("fun(boolean ...) " +
                "Number of args: " + a.length +
                " Contents: ");
       
        // using for each loop to display contents of a
        for(boolean x : a)
            System.out.print(x + " ");
       
        System.out.println();
    }
   
    public static void main(String args[])
    {
        // Calling overloaded fun() with different parameter
        fun(1, 2); //OK
        fun(true, false, false); //OK
        //fun(); // Error: Ambiguous!
    }
}


In above program, the overloading of fun( ) is perfectly correct. However, this program will not compile because of the following call:
fun(); // Error: Ambiguous!
According to (JLS 15.2.2), there are 3 phases used in overload resolution: First phase performs overload resolution without permitting boxing or unboxing conversion, Second phase performs overload resolution while allowing boxing and unboxing and Third phase allows overloading to be combined with variable arity methods, boxing, and unboxing. If no applicable method is found during these phases, then ambiguity occurs.

No comments:

Post a Comment