Java 方法的重载

方法重载概述
– 在同一个类中, 允许存在一个以上的同名方法, 只要它们
的参数个数或者参数类型不同即可。
• 方法重载特点
– 与返回值类型无关, 只看方法名和参数列表
– 在调用时, 虚拟机通过参数列表的不同来区分同名方法

package method.methodchongzai;

public class MethodChongZai {
    public static void main(String[] args) {
        int a = 1;
        int b = 2;
        int c = 3;
        System.out.println(sum(a,b,c));
        System.out.println(sum(a,b));
    }

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

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

输出如下:

package method.methodchongzai;

public class ChongZai2 {
        public static void main(String[] args) {
            //定义变量
            int a = 10;
            int b = 20;

            //求和方法
            int result = sum(a,b);
            System.out.println("result:"+result);

            //定义变量
            int c = 30;
            //求和方法
            //int result2 = sum2(a,b,c);
            int result2 = sum(a,b,c);
            System.out.println("result2:"+result2);

        }

        //不能出现方法名相同,并且参数列表也相同的情况
//    public static int sum(int x,int y) {
//        return x + y;
//    }

        public static float sum(float a,float b) {
            return a + b;
        }

        //求三个数据的和
    /*
    public static int sum2(int a,int b,int c) {
        return a + b + c;
    }
    */
        public static int sum(int a,int b,int c) {
            return a + b + c;
        }

        //求两个数据的和方法
        public static int sum(int a,int b) {
            //int c = a + b;
            //return c;

            return a + b;
        }

}

输出结果:

原文地址:https://www.cnblogs.com/longesang/p/10918513.html