Java中的方法重载机制/Overload

1、什么时候考虑方法重载?

     *   功能相似的时候,尽可能让方法名相同。

2、什么条件满足之后构成了方法重载?

     *   在同一个类当中

     *   方法名相同

     *   参数列表不同:

          -   数量不同

          -   顺序不同

          -   类型不同

3、方法重载和什么有关系,和什么没有关系?

    *   方法重载和方法名、参数列表有关系。

    *   方法重载和返回值类型没有关系。

    *   方法重载和修饰符列表没有关系。

4、方法重载的优点?

    *   方法重载可以让程序员使用功能相似的方法的时候就像在使用同一个方法一样,这样程序员以后编写代码比较方便。

比如以下代码:

public class Test {

    public static void main(String[] args) {
        int result1 = addInt(3,4);
        System.out.println(result1);
        float result2 = addFloat(3L,4L);
        System.out.println(result2);
        double result3 = addDouble(3.0,4.0);
        System.out.println(result3);
    }

    public static int addInt(int a,int b){
        int c = a + b;
        return c;
    }

    public static float addFloat(float a,float b){
        float c = a + b;
        return c;
    }

    public static double addDouble(double a,double b){
        double c = a + b;
        return c;
    }
}

然而利用方法重载机制可以改为:

public class Test {

    public static void main(String[] args) {
        int result1 = add(3,4);
        System.out.println(result1);
        float result2 = add(3L,4L);
        System.out.println(result2);
        double result3 = add(3.0,4.0);
        System.out.println(result3);
    }

    public static int add(int a,int b){
        int c = a + b;
        return c;
    }

    public static float add(float a,float b){
        float c = a + b;
        return c;
    }

    public static double add(double a,double b){
        double c = a + b;
        return c;
    }

 这样看起来就会美观,而且用起来也很方便。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

薰衣草2333

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值