Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ambiguous Overloaded method call resolved

When I call, call('a'); it output "char" and it is fine because char primitive type will take first priority over boxing it to Character.

static void call(char i){
    System.out.println("char");
}

static void call(Character i){
    System.out.println("Character");
}

How is call to call('a', 'a'); is ambiguous?

static void call(char i, Character j){
    System.out.println("char");
}

static void call(Character i, Character j){
    System.out.println("Character");
}

What I am thinking is for second parameter compiler has to go for Boxing and for first parameter perfect match is char primitive type, so call to call('a','a'); can be resolved to call(char i, Character j) method.

Obviously I am understanding it wrong, someone please explain this.

Some links where particular this kind of example is explained will be helpful.

like image 917
Jayesh Avatar asked Jan 06 '23 02:01

Jayesh


1 Answers

How is call to call('a', 'a'); is ambiguous?

Because in order for the (char i, Character j) overload to be applicable, the rules around boxing are brought into play - and at that point both calls are applicable. This is the second phase of determining the method signature (JLS 15.12.2):

  1. The first phase (§15.12.2.2) performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the second phase.

  2. The second phase (§15.12.2.3) performs overload resolution while allowing boxing and unboxing, but still precludes the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the third phase.

So in phase 2, both methods are applicable, but the rules for determining the most specific method (JLS 15.12.2.5) don't make either of the calls more specific than each other. It's not a matter of "unboxed is more specific than boxed" - it's a matter of "can I resolve this without any boxing" before "can I resolve this with boxing".

like image 188
Jon Skeet Avatar answered Jan 08 '23 17:01

Jon Skeet