---------------------- 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培训、期待与您交流!----------------------