When invoking a method from multiple overloading methods, For the matching method process, the Java compiler will perferance the order of primitive types (Widening Primitive Conversion), wrapper class (Boxing Conversion), and var-args. For example,
public class MyClass {
public void method(Long x, Long y) {
System.out.println("method(Long x, Long y)");
}
public void method(long x, long y) {
System.out.println("method(long x, long y)");
}
public void method(long... x) {
System.out.println("method(long... x)");
}
public static void main(String[] args) {
long x, y;
x = y = 0;
MyClass s = new MyClass();
s.method(x, y);
}
}
The result is "method(long x, long y)". The Java compiler will check for the matching primitive types, then it will search for the Wrapper types.
public class MyClass {
public void method(Long x, Long y) {
System.out.println("method(Long x, Long y)");
}
public void method(int x, int y) {
System.out.println("method(int x, int y)");
}
public void method(long... x) {
System.out.println("method(long... x)");
}
public static void main(String[] args) {
long x, y;
x = y = 0;
MyClass s = new MyClass();
s.method(x, y);
}
}
The result is "method(Long x, Long y)". The Java compiler gives preferance to the matching Wrapper class method signature other than the primitive varargs method.
public class MyClass {
public void method(Double x, Double y) {
System.out.println("method(Double x, (Double y)");
}
public void method(int x, int y) {
System.out.println("method(int x, int y)");
}
public void method(long... x) {
System.out.println("method(long... x)");
}
public static void main(String[] args) {
long x, y;
x = y = 0;
MyClass s = new MyClass();
s.method(x, y);
}
}
The result is "method(long ...x)". The compiler will not narrow down "long" primitive value to "int"; Also, it can not winden long to Double class. Only the var-args method can be used.
public class MyClass {
public void method(Long x, Long y) {
System.out.println("method(Long x, Long y)");
}
public static void main(String[] args) {
int x, y;
x = y = 0;
MyClass s = new MyClass();
s.method(x, y);
}
}
The arguments can not winden to "long" and then box to "Long". You will get compile error.