可变args重载 [英] Overloading with variable args
问题描述
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
}
}
该代码无法编译,编译器说f含糊不清.但是我认为第二种方法可以匹配f('b', 'c');
,这是什么问题?
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?
推荐答案
这是因为无法确定该方法调用是应该调用带有可变args的方法还是应该调用带有float和可变args的方法.
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决定用这种方法来调用widening> boxing>变量args,但是在这种情况下,两者都具有变量args.
Java decides with method to call in this way widening > boxing > variable args, however in this case both have variable args.
在这种情况下,基本将char扩展为浮动.
Basically char is being widened to float in this scenario.
java原语的扩展顺序为:
The widening order for java primitives is:
byte -> short -> int -> long -> float -> double
char -> int -> long -> float -> double
这篇关于可变args重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!