Java_log2000_重载函数之前的栗子再扩展

前面在这篇博客里面已经试验了一下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

而且可以确定的是,跟函数定义在代码中的先后顺序没有关系,新定义的三个函数放到形参为int函数前面最后一样输出int

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值