为什么类型提升优先于重载方法的varargs [英] Why does type-promotion take precedence over varargs for overloaded methods

查看:118
本文介绍了为什么类型提升优先于重载方法的varargs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class Test
{
    public static void printValue(int i, int j, int k)
    {
        System.out.println("int");
    }

    public static void printValue(byte...b)
    {
        System.out.println("long");
    }

    public static void main(String... args)
    {
        byte b = 9;
        printValue(b,b,b);
    }
}

上述代码的输出为int。但它应该是长的,因为字节类型参数函数已经存在。但是这里程序正在将字节值提升为int,但情况应该不是这样。

The output of the above code is "int". But it should be "long" because byte type argument function is already present. But here the program is promoting the byte values to int, but it should not be the case.

请问有人可以澄清这里发生了什么吗?

Please can someone clarify what is going on here?

推荐答案

在重载方法的情况下,变量参数方法将始终是编译器选择的最后一个方法。将字节提升为 int (加宽转换)将优先于采用var-arg的方法参数。

Variable argument methods will always be the last one to be chosen by the compiler in case of overloaded methods. Promotion of a byte to an int (widening-conversion) will be preferred over the method that takes a var-arg parameter.

这背后的原因是语言需要向后兼容。较旧的功能将优先于较新的功能。了解的简单方法JLS 说可变参数是扩大将击败拳击和拳击将击败var-args。

The reason behind this is that the language needs to be backward compatible. Older features will take priority over newer features. A simple way of understanding what the JLS says about variable arguments is that widening will beat boxing and boxing will beat var-args.

这篇关于为什么类型提升优先于重载方法的varargs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆