Reputation: 37038
I try to understand overloading rules which uses java compiler.
it is too hard for me.
public class Main {
public static void var(Long x) {
System.out.println("Long");
}
public static void var(int... x) {
System.out.println("int... x");
}
public static void main(String... args) {
var(5);
}
}
output:
int...
In Internet I found next rules:
- Primitive Widening > Boxing > Varargs.
- Widening and Boxing (WB) not allowed.
- Boxing and Widening (BW) allowed.
- While overloading, Widening + vararg and Boxing + vararg can only be used in a mutually exclusive manner i.e. not together.
- Widening between wrapper classes not allowed
but I cannot apply this rules to this code behaviour.
Can you help me?
my wrong version:
boxing int
-> Integer
and widening to Long
public class Main {
public static void var(Object x) {
System.out.println("Object");
}
public static void var(int... x) {
System.out.println("int... x");
}
public static void main(String... args) {
var(5);
}
}
output:
object
Upvotes: 2
Views: 159
Reputation: 213311
boxing
int
toInteger
and widening toLong
Although int
to Integer
boxing is fine, but Integer
to Long
is not a valid widening. Long
is not supertype of Integer
. So that's not valid. One option is widening followed by boxing. But such conversion is not allowed in Java. So the only option that is left is using varargs.
Upvotes: 2