前面在这篇博客里面已经试验了一下Java的函数重载,今天再扩展一下
问:当形参在byte,short,long,int之间选时,会输出哪个?
示例代码(在上一篇的基础上修改)
package float_or_double;
public class FloatOrDouble {
public static void aMethod(int a){
System.out.println("a="+a+" and is the int one!");
}
public static void aMethod(float a){
System.out.println("a="+a+" and is the float one!");
}
public static void aMethod(double a){
System.out.println("a="+a+" and is the double one!");
}
public static void aMethod(char a){
System.out.println("a="+a+" and is the char one!");
}
//below are updates
public static void aMethod(byte a){
System.out.println("a="+a+" and is the byte one!");
}
public static void aMethod(short a){
System.out.println("a="+a+" and is the short one!");
}
public static void aMethod(long a){
System.out.println("a="+a+" and is the long one!");
}
public static void main(String args[]){
aMethod(3.5);
aMethod(3.50);
aMethod(3.);
aMethod(3d);
aMethod(3f);
aMethod(3);
aMethod('c');
}
}
程序输出:
a=3.5 and is the double one!
a=3.5 and is the double one!
a=3.0 and is the double one!
a=3.0 and is the double one!
a=3.0 and is the float one!
a=3 and is the int one!
a=c and is the char one!
可以看到,仍然是选择int输出。
那么怎么才能调用我新加的函数呢?
main方法中加入
byte x=3;
short y=3;
long z=3;
aMethod(x);
aMethod(y);
aMethod(z);
即可输出:
a=3.5 and is the double one!
a=3.5 and is the double one!
a=3.0 and is the double one!
a=3.0 and is the double one!
a=3.0 and is the float one!
a=3 and is the int one!
a=3 and is the byte one!
a=3 and is the short one!
a=3 and is the long one!
a=c and is the char one!
在尝试新的变量定义时编辑器报错,算是一个小彩蛋吧~
//below are errors:
byte xx=3.0;//Type mismatch: cannot convert from double to byte
short yy=3.0;//Type mismatch: cannot convert from double to short
long zz=3.0;//Type mismatch: cannot convert from double to long