Overloading with variable args

半腔热情 提交于 2019-12-01 10:52:38

问题


class OverloadingVarargs2 {
    static void f(float i, Character... args) {
        System.out.println("first");
        System.out.println(i);
    }
    static void f(Character... args) {
        System.out.println("second");
    }
    static void test() {
        f(1, 'a');
        f('b', 'c'); // the method f is ambiguous
    }
}

This code can't be compiled, The compiler says that f is ambiguous. But I think the second method can match f('b', 'c'); what's the problem?


回答1:


That is because there is no way to determine if that method call should either call the one with variable args or the one with float and variable args.

Java decides with method to call in this way widening > boxing > variable args, however in this case both have variable args.

Basically char is being widened to float in this scenario.

The widening order for java primitives is:

byte -> short -> int -> long -> float -> double
char -> int -> long -> float -> double


来源:https://stackoverflow.com/questions/6476028/overloading-with-variable-args

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!