4

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.

VedantK
  • 9,728
  • 7
  • 66
  • 71
Mukesh
  • 182
  • 1
  • 2
  • 10

3 Answers3

5

Overloading resolution has three stages. The first stage tries to find a matching method without using auto-boxing and varargs (which is why meth(long i) is chosen and not meth(Integer i)). Only if the first stage doesn't find any match, the second stage tries to find a matching method with auto-boxing.

Eran
  • 387,369
  • 54
  • 702
  • 768
3

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.

SpringLearner
  • 13,738
  • 20
  • 78
  • 116
Vishal Gajera
  • 4,137
  • 5
  • 28
  • 55
0

I understand that here precedence is 1st is widening then autoboxing an then varargs. As widening a primitive parameter is much better than auto-boxing.

Mukesh
  • 182
  • 1
  • 2
  • 10