Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call overload method in java

Tags:

java

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

like image 824
Prasad V S Avatar asked Dec 08 '22 00:12

Prasad V S


2 Answers

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.

like image 167
Jon Skeet Avatar answered Dec 21 '22 15:12

Jon Skeet


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.

like image 29
Jan Avatar answered Dec 21 '22 15:12

Jan