您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Java中方法重载中的Varargs

Java中方法重载中的Varargs

You can either Widen or @R_435_2419@ but you cannot do both, unless you are @R_435_2419@ing and widening to Object (An int to Integer(@R_435_2419@ing) and then Integer to Object(Widening) is legal, since every class is a subclass of Object, so it is possible for Integer to be passed to Object parameter)

Similarly an int to Number is also legal (int -> Integer -> Number) Since Number is the super class of Integer it is possible.

public static void test(Integer...i)

public static void test(Float...f)

There are some rules that are followed when selecting which overloaded method to select, when @R_435_2419@ing, Widening, and Var-args are combined: -

So, based on the above given rules: -

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 1 to apply) : -

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 int where no widening is needed at all) is chosen. So 1st method will be invoked.

For more information, you can refer to JLS - Method Invocation Conversion

java 2022/1/1 18:14:31 有709人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶