Why widening beats both Boxing and var-args in Ove

2020-02-01 07:39发布

I am preparing for a SCJP exam and when studying widening part it's given that widening beats both Boxing and Var-args in overloading but there is no clear explanation. Tried searching but didnt get any better answer.

One answer i got is because the compiler chooses the older style before it chooses the newer style. But I am not convinced.

Edit: I know widening is preferrd than boxing and var-args. but WHY is my question. of which i know one. any other reasons.

标签: java
7条回答
看我几分像从前
2楼-- · 2020-02-01 08:23

Here is an example of it:

class Widen {

    private static void widen(long k) {
        System.out.println("Converted to long: " + k);
    }

    private static void widen(int ... k) {
        System.out.println("Converted to varargs: " + k);
    }

    private static void widen(Integer k) {
        System.out.println("Converted to Integer: " + k);
    }

    public static void main(String ... args) {
        int value = 3;
        widen(value);  // Output: Converted to long: 3
    }
}    

So all this means is that it will widen before autoboxing and using varargs. If we took out the method of widen with the long parameter, it would have chosen the autoboxing before the varargs.

查看更多
登录 后发表回答