"黑马程序员"-到底重载了哪个方法

---------------------- android培训java培训、期待与您交流!----------------------

/*
方法重载
*/
class  OverrideTest
{
	public void info(String name,double count){
		System.out.println("name参数为:"+name+"\ncount参数为:"+count);
	}
	public static void main(String[] args) 
	{
		new OverrideTest().info("hello",8);
	}
}
结果:


name参数为:hello
count参数为:8.0

根据得出的结果。实参8自动转型为8.0,int类自动向上提升了,为double类型。
说明了jvm在调动方法时自动为方法中的形参进行向上转型。


class OverrideTest2 
{
	public void info(String name,double count){
		System.out.println("name参数为:"+name+"\ncount参数为:"+count);
	}
	public void info(String name,int count){
		System.out.println("name参数为:"+name+"\ncount参数为:"+count);
	}
	public static void main(String[] args) 
	{
		new OverrideTest2().info("hello",8);
	}
}

结果:

name参数为:hello
count参数为:8

在调用info()方法时。传入的形参类型为info(String,int),毫无以为jvm会识别并且调用info(String name,int count)方法。
这也说明了。java重载解析过程中:jvm首先选取所有匹配调用的方法,然后在次筛选出匹配最为精确的方法。
对于info("hello",8)当然会匹配info(String,int)方法而不是info(String,double)方法。

class OverrideTest3 
{
	public void info(Object obj,double count){
		System.out.println("obj参数为:"+obj);
		System.out.println("count参数为:"+count);
	}
	public void info(Object[] objs,double count){
		System.out.println("objs参数为:"+objs);
		System.out.println("count参数为:"+count);
	}
	public static void main(String[] args) 
	{
		new OverrideTest3().info(null,8);
	}
}

结果:


objs参数为:null
count参数为:8.0

很显然调用了info(Object[] objs,double)方法。null也可是视为一个对象,而不是一个数组。它应该调用info(Object,double)才对呀?
根据匹配的原则,当实际调用时传入的实参都满足多个方法时,如果某个方法的形参要求的范围越小,那么这个方法
就越精确。Object[]可以看做为Object的子类,所以info(Object[] objs,double count)的方法略微精确,此时才会调用
这个方法。


class OverrideTest4 
{
	public void info(Object obj,int count){
		System.out.println("obj参数为:"+obj);
		System.out.println("count参数为:"+count);
	}
	public void info(Object[] objs,double count){
		System.out.println("objs参数为:"+objs);
		System.out.println("count参数为:"+count);
	}
	public static void main(String[] args) 
	{
		new OverrideTest4().info(null,8);
	}
}

结果:

OverrideTest4.java:13: 对 info 的引用不明确,
OverrideTest4 中的 方法 info(java.lang.Object,int) 
和 OverrideTest4 中的方法 info(java.lang.Object[],double)都匹配
                new OverrideTest4().info(null,8);
                                   ^
1 错误

同样的是info(null,8),这里却不能通过编译。
我们在来一步一步分析,根据匹配原则,当实际调用时传入的实参满足多个方法时,如果某个方法的形参要求参数范围越小就越精确。
Object[]可以看成Object子类所以info(null)房中的实参,但是此方法中一个实参类型为int,这样也导致满足info(Object obj,int count)这个方法。
最终导致两个方法都满足,这样编译器就无法匹配哪个才是最精确的了。

---------------------- android培训java培训、期待与您交流!----------------------


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值