Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method invocation conversions [duplicate]

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.

like image 985
Mukesh Avatar asked Feb 08 '23 16:02

Mukesh


1 Answers

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.

like image 168
Eran Avatar answered Feb 16 '23 02:02

Eran