java方法重载

java方法重载

1什么是方法重载
当你在一个类中看到同名的但是参数个数或者类型不同的方法时,就发生了方法重载
2,分类
①通过改变参数的数目

class Math{
    int sum (int x,int y){
        return x + y;
    }
    int sum(int x,int  y,int z){
        return x + y + z;
    }
}

    public class ex {
        public static void main(String[] args) {
           Math c = new Math();
            System.out.println(c.sum(1,2));
            System.out.println(c.sum(1,2, 3));class Math{
    int sum (int x,int y){
        return x + y;
    }
    int sum(int x,int  y,int z){
        return x + y + z;
    }
}

    public class ex {
        public static void main(String[] args) {
           Math c = new Math();
            System.out.println(c.sum(1,2));
            System.out.println(c.sum(1,2, 3));


        }
    }

        }
    }

结果

3
6

Process finished with exit code 0

②通过改变参数的类型

class Math{
    int sum (int x,int y){
        return x + y;
    }
    double sum(int x,double y){
        return x + y ;
    }
}

    public class ex {
        public static void main(String[] args) {
           Math c = new Math();
            System.out.println(c.sum(1,2));
            System.out.println(c.sum(1,2.2));


        }
    }

结果

3
3.2

Process finished with exit code 0

3,不能只通过更改返回值的类型来进行重载,会存在歧义
先看一下下面的代码

class Math{
    int sum (int x,int y){
        return x + y;
    }
    doulbe sum(int x,int  y){
        return x + y ;
    }
}

    public class ex {
        public static void main(String[] args) {
           Math c = new Math();
            System.out.println(c.sum(1,2));


        }
    }

当c 去调用sum方法时,编译器根本分不清你到底想用哪个一方法,接收的参数类型和数目都是一样的,又因为编译错误要比运行时错误好的多。所以java中不允许仅仅通过改变返回值类型来重载。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值