我正在学习Java。当我调用
go(x)
时,我得到“int”。为什么不“短”?
public class test {
public static void go(Short n) {System.out.println("Short");}
public static void go(int n) {System.out.println("int");}
public static void main(String[] args) {
short x=11;
go(x);
}
}
基于https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.3:
方法调用转换应用于一个中的每个参数值 方法或构造函数调用(§8.8.7.1、§15.9、§15.12):类型 参数表达式的类型必须转换为 相应的参数。
方法调用上下文允许使用以下之一:
身份转换(§5.1.1)
扩大原始转换(§5.1.2)
扩大参考转换(§5.1.5)
装箱转换(§5.1.7)可选地后跟扩大参考 转换
拆箱转换(§5.1.8)可选地后跟一个扩大 原始转换。
您正在尝试调用一个方法,虽然在上面的 Java 语言规范中没有明确提及,但是扩大原始转换(即,将 short 转换为 int)优先于自动装箱(即,将 short 转换为 Short)。