问题
类A中有两个overload方法:
void B(Object o)
void B(Number n)
客户端程序
new A().B(Integer.valueOf(1))调用的是哪个B方法?还是说这段代码无法通过编译?
上手编程
public class A {
void B(Object o) {
System.out.println("0");
}
void B(Number n) {
System.out.println("1");
}
}
public class Main {
public static void main(String[] args) {
A a = new A();
a.B(Integer.valueOf(1));
}
}
执行,程序通过编译,并输出
1
说明main方法中调用了方法void B(Number n)。
原因探究
Integer. valueOf()可以将基本类型int转换为包装类型Integer,或者将String转换成Integer。在main方法中A类的实例化a所调用的B方法的参数显然为Integer类型。
Integer类型的部分源码如下:
public final class Integer extends Number implements Comparable<Integer> {
/**
* A constant holding the minimum value an {@code int} can
* have, -2<sup>31</sup>.
*/
@Native public static final int MIN_VALUE = 0x80000000;
/**
* A constant holding the maximum value an {@code int} can
* have, 2<sup>31</sup>-1.
*/
@Native public static final int MAX_VALUE = 0x7fffffff;
/**
* The {@code Class} instance representing the primitive type
* {@code int}.
*
* @since JDK1.1
*/
@SuppressWarnings("unchecked")
public static final Class<Integer> TYPE = (Class<Integer>) Class.getPrimitiveClass("int");
...
可以看出Integer类继承了Number类,显然其也继承了Object类。在这里我们需要知道重载方法的匹配是有优先级的,如下:
重载方法的优先级:
1.先匹配参数个数
2.参数类型的最佳匹配:直接所属类
3.如果没有找到直接所属类,会发生向上转型,直至找父类参数,直观上查找顺序为:包装类-》父类-》接口
4.如果向上转型仍无法匹配,则查找可变参数列表
5.以上无法匹配返回找不到方法错误。
因此该程序执行了第二个重载的B方法。