10

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 
0

3 Answers 3

12

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.

Sign up to request clarification or add additional context in comments.

Comments

6

The statement f('a', 'b'); is ambiguous, because the compiler cannot infer which exact method to invoke.

The reason behind this is that he char primitive type is considered as numeric (for each character there's a corresponding non-negative integer value between 0 and 65535).

That is why the compiler cannot infer if the parameter 'a' stands for the integer value of 97, which should be then cast to float or 'a' stands for the character 'a' which should be then autoboxed to Character.

Comments

3

this causes trouble because

f('a', 'b');

'a' can be converted to int and hence passed to float in the first f().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.