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;
        }

}

輸出結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM