overload重载

方法的重载

 1 /**
 2  * 重载 overload
 3  * @author Administrator
 4  *同一个类,同一个方法
 5  *不同:参数列表不同(类型,个数,顺序) 只和 参数列表有关
 6  *    跟  返回值 和 形参无关
 7  *     构造方法也可以重载
 8  */
 9 public class TestOverload {
10     public static void main(String[] args) {
11         MyMath m = new MyMath();
12         int result = m.add(4, 5);
13         
14         double result2 = m.add(4.1, 5);
15         double result3 = m.add(4, 5.1);
16         double result4 = m.add(4.1, 5.1);
17         int result5 = m.add(4, 5, 6);
18         
19         System.out.println("result="+result+"	"+"result2="+result2+"	"+"result3="+result3+"	"+"result4="+result4+"	"+"result5="+result5);
20     }
21 }
22 class MyMath{
23     int a;
24     int b;
25     // 构造方法重载 
26     
27     public MyMath(){
28         
29     }
30     public MyMath(int a){
31         this.a=a;
32     }
33     /*
34      * 这个为何报错?因为 会有歧义 他和 int a只是名字不同 到底是定义a 还是b呢?
35      * 所以如果有2个要定义的 参数 就 都写出来 防止歧义
36     public MyMath(int b){
37         this.b=b;
38     }
39     */
40     //这样就没有歧义了
41     public MyMath(int a,int b){
42         this.a=a;
43         this.b=b;
44     }
45     
46     
47     
48     //普通方法重载
49     public int add(int a,int b){
50         return a+b;
51     }
52     public double add(double a,int b){
53         return (double)(a+b);
54     }
55     public double add(int a,double b){
56         return (double)(a+b);
57     }
58     public double add(double a,double b){
59         return a+b;
60     }
61     public int add(int a,int b,int c){
62         return a+b+c;
63     }
64 }
原文地址:https://www.cnblogs.com/PoeticalJustice/p/7608656.html