Java方法重載的區分


測試程序代碼:

 
        
 1   class Computer {
 2     private int x;
 3 
 4     public Computer(){
 5         this(10);
 6     }
 7 
 8     /**
 9      * 構造方法重載
10      * @param x
11      */
12     public Computer(int x){
13         this.x=x;
14     }
15     /**
16      * 根據參數個數不同的方法重載
17      * @param a
18      * @param b
19      * @return
20      */
21     public  int max(int a,int b){
22         return max(a,b,Integer.MIN_VALUE);//Integer.MIN_VALUE是int類型中最小數-2147483648
23     }
24     public  int max(int a,int b,int c){
25         int max=a;
26         if (max<b) max=b;
27         if (max<c) max=c;
28         return max;
29     }
30     /**
31      * 根據參數類型不同方法(函數)重載
32      * @param x
33      * @return
34      */
35     public int add(int x){
36         return x;
37     }
38     public float add(float x){
39         return x;
40     }
41 
42     /**
43      * 測試方法的返回值是否可以作為重載的標准
44      * @return
45      */
46 //    public int returnValue(){
47 //        return 5;
48 //    }
49 //    public float returnValue(){
50 //        return 5;
51 //    }
52 //    編譯器報錯,returnValue方法已經存在。很明顯根據返回值類型是不可以判斷方法是否重載的。
53 }
54 class OverLoading{
55     public void test(){
56         Computer computer=new Computer();
57         new Computer(100);
58         int max_2=computer.max(10,11);
59         int max_3=computer.max(10,29,33);
60         int tmp1=computer.add(10);
61         float tmp2=computer.add(10f);
62     }
63 }
 
         
         
        

結論:判斷方法(函數)重載的依據是參數個數的不同和參數類型的不同,根據返回值類型的不同是不可以判斷方法重載。

關聯博客(CSDN):https://blog.csdn.net/m0_38022608/article/details/80251993

歡迎私下交流編程技術!(QQ:2187093468)


免責聲明!

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



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