您可以
Widen或
Box,但你不能两者都做,除非你是
boxing and widening到
Object(一个int,整数(拳击),然后整型
对象(加宽)是合法的,因为每个类的子类
Object,所以它有可能Integer被传递到Object参数)
同样,
intto
Number也是合法的
(int-> Integer-> Number),因为
Number是它的超类
Integer。
让我们在您的示例中看到以下内容:
public static void test(Integer...i)public static void test(Float...f)
当选择Boxing,Widening和Var-args组合在一起时,选择某些重载方法时要遵循以下规则:-
- 基本扩展使用smallest可能的方法参数
- 包装器类型无法扩展为其他包装器类型
- 您可以将Box从int更改为Integer,然后将其扩展为Object,但不能将其扩展为Long。
- 加宽节拍,搏击节拍可变参数。
- 您可以先装箱,然后加宽(int可以Object通过变成Integer)
- 您无法加宽,然后Box(int不能变成Long)
- 您不能将var-args与扩大或装箱结合使用
因此,根据上述给定规则:
当您将两个整数传递给上述函数时,
根据规 则3,必须先将其放入Widened,然后再Boxed放入Long,根据规则5这是非法的(您不能先加宽,然后再加上Box)。
因此,将其装箱以存储在
Integervar-args
中。
但是在第一种情况下,您具有具有var-args原始类型的方法:
public static void test(int...i)public static void test(float...f)
Then
test(1, 2)can invoke both the methods (Since neither of them is more
suitable for
rule 1to apply) : -
- In first case it will be
var-args
- In second case, it will be Widening and then Var-args (which is allowed)
Now, when you have methods with exactly one int and one flost: -
public static void test(int i)public static void test(float f)
Then on invoking using
test(1), rule 1 is followed, and smallest possible
widening (i.e. the
intwhere no widening is needed at all) is chosen. So 1st
method will be invoked.
For more information, you can refer to
JLS - Method InvocationConversion
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)