首先来谈一下方法重载:所谓方法重载就是在同一个类里,定义同一方法名,但是形式参数不同,以至于达到不同的功能。
通常我们常有的例子就是求几个数的和,那么到底是几个数尼:
public static int sum(int a,int b){ //求两个数
return a+b;
}
public static int sum(int a,int b,int c) { //求三个数
return a+b+c;
}
public static double sum(double a,double b){ //求两个浮点类型的数
return a+b;
}
由上述可见,对于几个固定的数我们都是有特定的方法,那么我们求大量不同参数类型的和时不可能去定义那么多个方法那么可变参编程来了;
public static int sum(int... a){
int ret = 0;
for(int x:a){
ret += x;
}
return ret;
}
//此时我们实参的值可以如下传:
sum(1,2,3,4,5,6,7);
sum(new int[]{1,3,4,5});
int[] a = {1,2,3};
sum(a);