一个问题

问题

类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方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值