这个问题很orz,非常的帮
我就想问问各位读者,这会输出什么??
很明显,第一眼上去就很纠结,看着输出这个是对的,输出那个是对的,非常纠结。
最终输出:
#############byte #############int没错,就是这样。
再来看看代码:
public class TestMianSi02 { public static void main(String[] args) { byte b=10; //第一波测试 test(b); } public static void test(short s){ System.out.println("#############short"); } public static void test(char c){ System.out.println("#############char"); } public static void test(int i){ System.out.println("#############int"); } }想想这会输出什么??
最终输出的是。。。。
#############short从上面就可以看出,这里是有转换调用规则的。
我们在这篇博客能够知道,方法参数是引用类型的时候,重载方法是根据类的继承树调用的。而这里的参数是基本类型!我们该怎么判断呢??
通过字节大小!!
byte : 1字节(8位) short : 2字节(16位) char : 2(16位) int : 4(32位)当我们b是byte类型的时候,既然方法里面有byte类型的参数,那么我们就调用byte参数类型的方法。 当byte类型参数的方法没有了,那么将会把byte类型8位提升为16位的short,然后调用short类型参数的方法。
没错,就是这样!!!
好!再来,看看你是否还能够猜对:
public class TestMianSi02 { public static void main(String[] args) { byte b=10; //第一波测试 test(b); } public static void test(char c){ System.out.println("#############char"); } public static void test(int i){ System.out.println("#############int"); } }最终输出:
#############int但是呢??char虽然是16位的,但是它的取值范围是没有负数的,是大于等于零的,导致无法转换。所以当只有char类型参数和int类型参数的方法的时候将会调用int类型参数方法。
好了,Nice!!!