java中的方法重载解析 [英] Method overload resolution in java
问题描述
以下是我对java中重载解析的了解:
Here is what I know about overload resolution in java:
尝试从给定的
重载方法定义解析方法调用的编译器称为重载解析。如果
编译器找不到完全匹配,则它仅通过使用upcast来查找最接近的匹配
(从不进行向下转换)。
The process of compiler trying to resolve the method call from given overloaded method definitions is called overload resolution. If the compiler can not find the exact match it looks for the closest match by using upcasts only (downcasts are never done).
这是一个类:
Here is a class:
public class MyTest {
public static void main(String[] args) {
MyTest test = new MyTest();
Integer i = 9;
test.TestOverLoad(i);
}
void TestOverLoad(int a){
System.out.println(8);
}
void TestOverLoad(Object a){
System.out.println(10);
}
}
正如预期的那样,输出为10。
As expected the output is 10.
但是,如果我稍微更改类定义并更改第二个重载方法。
However if I change the class definition slightly and change the second overloaded method.
public class MyTest {
public static void main(String[] args) {
MyTest test = new MyTest();
Integer i = 9;
test.TestOverLoad(i);
}
void TestOverLoad(int a){
System.out.println(8);
}
void TestOverLoad(String a){
System.out.println(10);
}
}
输出为8。
我很困惑。如果永远不会使用向下转换,那为什么8会被打印出来呢?为什么编译器选择 TestOverLoad
方法,该方法将 int
作为参数从整数
到 int
?
Here I am confused. If downcasting was never to be used, then why did 8 get printed at all? Why did compiler pick up the TestOverLoad
method which takes int
as an argument which is a downcast from Integer
to int
?
推荐答案
编译器将考虑不是向下转换,而是为重载解析进行拆箱转换。这里,整数
i
将被取消装箱到 int
成功。不考虑 String
方法,因为 Integer
无法扩展为 String
。唯一可能的重载是考虑拆箱的那个,所以打印 8
。
The compiler will consider not a downcast, but an unboxing conversion for overload resolution. Here, the Integer
i
will be unboxed to an int
successfully. The String
method isn't considered because an Integer
cannot be widened to a String
. The only possible overload is the one that considers unboxing, so 8
is printed.
第一个代码的原因输出 10
是编译器会考虑扩展引用转换( Integer
到 Object
)通过拆箱转换。
The reason that the first code's output is 10
is that the compiler will consider a widening reference conversion (Integer
to Object
) over an unboxing conversion.
JLS的第15.12.2节,在考虑适用的方法时,请说明:
Section 15.12.2 of the JLS, when considering which methods are applicable, states:
- 第一阶段(§15.12.2.2)执行重载解析而不允许装箱或拆箱转换,或使用变量arity方法调用。如果在此阶段没有找到适用的方法,则处理继续到第二阶段。
- 第二阶段(§15.12.2.3)执行重载解析,同时允许装箱和拆箱[...]
这篇关于java中的方法重载解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!