Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method ambiguous when overloading with variable argument

I am a newcomer into Java. Today I saw a piece of code in "Thinking in Java", but I cannot figure out why it produce compile time error.

Code:

public class OverloadingVarargs2 {
    static void f(float i, Character... args) {
        System.out.println("first");
    }
    static void f(Character... args) {
        System.out.println("second");
    }
    public static void main(String[] args) {
        f(1, 'a');
        f('a', 'b');
    }
}

Compile complained:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    The method f(float, Character[]) is ambiguous for the type OverloadingVarargs2 
like image 940
Feng Yu Avatar asked Nov 19 '15 14:11

Feng Yu


1 Answers

The problem is with f('a', 'b');

Both methods have a vararg argument, which means they will both be considered on the third and final phase of overloading resolution.

'a' is a char, which can be automatically converted to float via Widening Primitive Conversion.

Both 'a' and 'b' can be converted from char to Character using Boxing Conversion.

Therefore both f(float i, Character... args) and f(Character... args) are applicable for the arguments 'a' and 'b', and none of them has a precedence over the other.

like image 108
Eran Avatar answered Nov 15 '22 20:11

Eran