简体   繁体   中英

Method Overloading with varargs

I am a bit confused about this topic, reason being in this code:

public class File
{
    public static void main(String[] args)
    {
        numbers();
    }

    static void numbers(int...x)
    {
        System.out.println("Integers");
    }
    static void numbers(byte...x)
    {
        System.out.println("Byte");
    }
    static void numbers(short...x)
    {
        System.out.println("Short");
    }
}

The output of this code is "Byte", and the reason is the most specific type is chosen, since among byte , short and int the most specific type is byte , that's why it is chosen.

But if I modify my code to-

public class File
{
    public static void main(String[] args)
    {
        numbers(1, 4);
    }

    static void numbers(int...x)
    {
        System.out.println("Integers");
    }
    static void numbers(byte...x)
    {
        System.out.println("Byte");
    }
    static void numbers(short...x)
    {
        System.out.println("Short");
    }
}

The output is "Integers", and I'm unable to figure out why? I know in case of arithmetic instructions byte and short are implicitly promoted to int , but here we are calling a method with values which is within the range of byte and short , then how the method with int arguments is invoked?

And also, if I comment out the method with int arguments, then the code shows an error of no suitable method found. Why???

1 and 4 are integer literals. So the int... version is called.

There are no byte or short literals, but if you were to call Numbers((byte)2, (byte)3); the byte... version would be called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM