java 方法重載

來源:互聯網
上載者:User

標籤:ret   dem   參數順序   相關   結果   定義   span   static   rgs   

Java允許在一個類中定義多個名稱相同的方法,但是參數的類型或個數必須不同,這就是方法的重載。

public class MethodDemo03 {    public static void main(String[] args) {        // 下面是針對求和方法的調用        int sum1 = add(1, 2);            int sum2 = add(1, 2, 3);        double sum3 = add(1.2, 2.3);        // 下面的代碼是列印求和的結果        System.out.println("sum1=" + sum1);        System.out.println("sum2=" + sum2);        System.out.println("sum3=" + sum3);    }    // 下面的方法實現了兩個整數相加    public static int add(int x, int y) {        return x + y;    }    // 下面的方法實現了三個整數相加    public static int add(int x, int y, int z) {        return x + y + z;    }    // 下面的方法實現了兩個小數相加    public static double add(double x, double y) {        return x + y;    }}

在main()方法中調用add()方法時,通過傳入不同的參數便可以確定調用哪個重載的方法,如add(1,2)調用的是兩個整數求和的方法。值得注意的是,方法的重載與傳回值類型無關,它只有兩個條件,一是方法名相同,二是參數個數或參數類型不相同。

l 重載方法參數必須不同:

參數個數不同,如method(int x)與method(int x,int y)不同

參數類型不同,如method(int x)與method(double x)不同g

參數順序不同,如method(int x,double y)與method(double x,int y)不同

l 重載只與方法名與參數類型相關與傳回值無關

如void method(int x)與int method(int y)不是方法重載,不能同時存在

l 重載與具體的變數標識符無關

如method(int x)與method(int y)不是方法重載,不能同時存在

 

java 方法重載

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.