Java方法的重载

Java方法的重载

方法重载:在类中方法名称相同,但是形式参数不同

public class Demo15 {
    public static void main(String[] args) {
      int sum=  max(30,30);
        System.out.println(sum);
        double sumDouble = max(33.2,55.4);

    }
    public static int max(int a,int b){
        int result = 0;
        if (a==b){
            System.out.println("a==b");
            return 0;

        }
        if (a>b){
            result = a;
        }else {
            result = b;
        }
        return result;

    }//方法的名称相同都是max
    public static int max(int c,int d){
        int result = 0;
        if (a==b){
            System.out.println("a==b");
            return 0;

        }
        if (a>b){
            result = a;
        }else {
            result = b;
        }
        return result;

    }//这样的写法是错误的因为方法名相同而且形式参数也相同
    // 系统无法识别
    public static double max(double a,double b){

        if(a==b){
            System.out.println("a==b");
            return 0;
        }
        if (a>b){
            return a;
        }else {
            return b;

        }

    }//但是方法的类型不同double和int
     public static double max(double a,double b,double c){

        if (a==b && b==c){
            System.out.println("a==b==c");
            return 0;

        }
        if (a>b && a>c){
            return a;
        }else if(b>a && b>c){
            return b;
        }else if (c>a && c>b){
            return c;
        } return 0;
        }
        //形式参数个数不同也可以
    public static int max(int a,int b,int c){//方法名字相同个数不同但是实现的功能却全然不同
                                            //这也是重载
        return a+b+c;
    }
}

总结重载的实现条件:

  • 在类中方法名字必须相同
  • 形式参数必须不同(类型不同,个数不同)
  • 重载后实现的功能也可以不同
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值