Method call conversions

I tried to understand how overloaded methods are invoked using transformations. Let me explain my question with an example that 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's the conclusion: Long

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

+4
source share
3 answers

While the overloaded form method appears and the user tries to call among the then selected compiler,

  • Exact match with the data type, if find, then calls immediately. 1.1, if the exact match does not match, then the compiler will try to combine with a wider type of data type.

  • , -.

  • ​​2 , vararg.
  • , cann't .

5 integer(primitive), int '(1 ), , . , long (), , 'int'

, "long".

, .

+2

. varargs ( meth(long i), meth(Integer i)). , .

+5

I understand that here the priority of the 1st increases, and then varargs then autoboxes. Since the extension of a primitive parameter is much better than auto-boxing.

0
source

Source: https://habr.com/ru/post/1613604/


All Articles