当重载包含不匹配参数的方法时,JVM 将始终使用具有比参数更宽的最小参数的方法。
我已经通过以下两个示例确认了上述内容:
加宽:字节加宽到 int
class ScjpTest{
static void go(int x){System.out.println("In Int");}
static void go(long x){System.out.println("In long");}
public static void main (String[] args){
byte b = 5;
go(b);
}
}
装箱:将 int 装箱为 Integer
class ScjpTest{
static void go(Integer x){System.out.println("In Int");}
static void go(Long x){System.out.println("In Long");}
public static void main (String[] args){
int b = 5;
go(b);
}
}
上述两个示例都输出正确的“In Int”。当情况涉及 var-args 时,我很困惑,如下例所示
class ScjpTest{
static void go(int... x){System.out.println("In Int");}
static void go(long... x){System.out.println("In lInt");}
public static void main (String[] args){
byte b = 5; //or even with: int b = 5
go(b);
}
}
以上产生以下错误:
ScjpTest.java:14: reference to go is ambiguous, both method go(int...) in ScjpTest and method go(long...) in ScjpTest match
go(b);
^
1 error
为什么它不应用与前面示例中相同的规则?即将字节扩大到一个int,因为它是大于字节的最小的?