java中,存在C++没有的一种重载方法,即可变个数的形参,合理使用可变个数的形参,可以更好地提高编程效率。
/*
- 可变个数的形参:
- 1.格式:对于方法的形参:数据类型 … 形参名
- 2.可变个数形参的方法与同名的方法之间构成重载
- 3.可变个数的形参在调用时,个数从0开始,到无穷多个
- 4.使用可变多个形参的方法与方法的形参使用数组是一致的
- 5.若方法中存在可变个数的形参,那么一定要声明在方法形参的最后
- 6.在一个方法中,最多只有一个可变个数的形参
*/
解释:
3.可变个数的形参在调用时,个数从0开始,到无穷多个。
当程序中存在个数为0到无穷多个的重载方法时,程序优先调用重载方法。
例如:
public class test_array {
public static void main(String[] args) {
test_array t=new test_array();//新建对象
t.sayHello();
t.sayHello("hello china","hello Beijing");
}
public void sayHello() {
System.out.println("hello world!");
}
//可变个数形参的方法
public void sayHello(String ... args) {
for(int i=0;i<args.length;i++) {
System.out.println(args[i]);
}
System.out.println("====");
}
}
在运行程序时,会优先调用sayHello() ,再调用sayHello(String … args),输出
将重载函数sayHello()注释掉,
public class test_array {
public static void main(String[] args) {
test_array t=new test_array();//新建对象
t.sayHello();
t.sayHello("hello china","hello Beijing");
//t.sayHello("hello","hello world");
}
/*
* public void sayHello() { System.out.println("hello world!"); }
*/
//可变个数形参的方法
public void sayHello(String ... args) {
for(int i=0;i<args.length;i++) {
System.out.println(args[i]);
}
System.out.println("====");
}
}
则会直接调用可变个数形参的方法,输出
解释:
4.使用可变多个形参的方法与方法的形参使用数组是一致的。
所以,在程序中,可变多个形参的方法名称和使用形参数组的方法名称不能一样,否则会报错,其他的,如调用方法,内容等都可以一致。
如:
public void sayHello(String ... args) {
for(int i=0;i<args.length;i++) {
System.out.println(args[i]);
}
System.out.println("====");
}
public void sayHello(String[] args) {
for(int i=0;i<args.length;i++) {
System.out.println(args[i]);
}
System.out.println("*****");
}
会报Duplicate method sayHello(String ...) in type test_array
错误
传参也可以使用匿名函数传参。
t.sayHello(new String[] {"hello china","hello Beijing"});
解释:
- 5.若方法中存在可变个数的形参,那么一定要声明在方法形参的最后
- 6.在一个方法中,最多只有一个可变个数的形参。
因为可变个数的形参不确定,所以当public void sayHello(String ... args,int i) {}会报错,
无法确定传入的参数究竟是String类型还是int类型。
只能使用public void sayHello(int i,String ... args) {}
同样因为上述原因,在一个方法中,最多只有一个可变个数的形参。