public class OverLoad {
void method(Integer i){
System.out.println("Integer "+i);
}
void method(int i){
System.out.println("in "+i);
}
public static void main(String a[]){
OverLoad m= new OverLoad();
m.method(2); //it calls method(int i) why?
}
}
If i call the m.method(3)
it will call the int method why?
If i call the m.method((Integer)3)
then it will call the Integer method.
By default it going into primitive data type
By default it going into primitive data type
Well yes, because that's the exact type of the argument. The type of the literal 2
is int
, not Integer
(JLS 3.10.1). It's convertible to Integer
via a boxing conversion (JLS 5.1.7), but that will only happen if it's actually needed.
Overloading in Java occurs in three phases, as per JLS 15.12.2:
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.
So m.method(2)
matches method(int)
in the first phase, so doesn't need to proceed to the second phase.
That's because 2 is a primitive integer - not an object of type Integer
.
Autoboxing will only occur if no perfect match signature (with int) would be found.
And by calling with arguments (Integer)3
you force the compiler into autoboxing your int
3
into an Integer
object as well.
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