包装加宽是否胜过拆箱?
class Dec26 {
public static void main(String[] args) {
short a1 = 6;
new Dec26().go(a1);
new Dec26().go(new Integer(7));
}
void go(Short x) { System.out.print("S "); }
void go(Long x) { System.out.print("L "); }
void go(int x) { System.out.print("i "); }
void go(Number n) { System.out.print("N "); }
}
输出:
i N
在上面的示例中,为什么编译器选择加宽选项(即 Integer --> Number)而不是拆箱 Integer 并选择 int 选项?
谢谢
class Dec26 {
public static void main(String[] args) {
short a1 = 6;
new Dec26().go(a1);
new Dec26().go(new Integer(7));
}
void go(Short x) { System.out.print("S "); }
void go(Long x) { System.out.print("L "); }
void go(int x) { System.out.print("i "); }
void go(Number n) { System.out.print("N "); }
}
Output:
i N
In the above example, why does the compiler choose the widening option (i.e. Integer --> Number) instead of unboxing the Integer and choosing the int option?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的问题不是关于一般转换的优先级,而是关于重载解析算法的细节。
出于向后兼容性的原因,重载决策过程由 3 个阶段组成:
如果编译器在一个阶段无法识别潜在适用的方法,它会进入下一阶段,过度分析潜在适用的方法以选择最具体的方法并将其用于调用。
如您所见,在您的情况下,两种调用都可以通过子类型应用(
short
是int
的子类型,Integer
是int
的子类型>Number),因此它们在第 1 阶段解析,因此重载解析过程永远不会到达第 2 阶段,并且可能的拆箱被忽略。另请参阅:
Your question is not about precedence of conversions in general, it's about details of overload resolution algorithm.
For backward compatibility reasons, process of overload resolution consists of 3 phases:
If compiler fails to identify potentially applicable methods at one phase, it proceeds to the next one, overwise it analyzes potentially applicable methods to choose the most specific one and uses it for the invocation.
As you can see, in your case both invocations are applicable by subtyping (
short
is a subtype ofint
,Integer
is a subtype ofNumber
), therefore they are resolved on phase 1, so that overload resolution process never reaches phase 2 and possible unboxing is ignored.See also:
我认为对象优先于原始类型。
I think the object has the precedence against the primitive type.