Search code examples
javaautoboxing

Method invocation conversions


I was trying to understand how the overloaded methods are called with conversions.Let me explain my question with a example I am trying

public class Autoboxing {

    public void meth(Integer i){
        System.out.println("Integer");
    }
    public void meth(long i){
        System.out.println("Long");
    }
    public void meth(int... i){
        System.out.println("int");
    }

    public void meth(Object i){
        System.out.println("Object");
    }

    public static void main(String[] args) {
        Autoboxing box= new Autoboxing();
        box.meth(5);
    }
}

here output is : Long

Why method with argument long is called instead in Wrapper Integer.Please explain.


Solution

  • While Method Overloaded form comes and user try to invoke among of then compiler chosen in this manner,

    1. Exact match with data-type if find then invoke immediatly. 1.1 if exact match not match then compiler try to match with broader type-data type.

    2. if above case fail then it start to match with Auto-Boxing manner.

    3. all above 2-case fail then start to match with vararg case.
    4. all above case failure while gives error like cann't resolve method-name.

    so in your case 5 is integer(primitive) so it start to match with int' (1-case), but fail so try to match with broader data-type. here, in your case it match with long(primitive) which is broader then 'int'

    So, that you get "Long" output.

    So, likewise compiler behaviors while overloading scenario came.