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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With