overload方法重载
1、概念:一个类中的一组方法具有相同的名字,有不同(参数个数、参数类型、参数顺序)的参数列表。
2、作用:运用一个方法名,实现对不同参数的方法调用。
典型的方法重载:
3、设计重载方法:通过方法参数类型来定位方法;如果传递的时候没有这个类型,会自动进行类型转化
public class Test {
public void test(int i){
System.out.println("执行test方法int类型:" + i);
}
public void test(boolean b){
System.out.println("执行test方法boolean类型:" + b);
}
public void test(String string){
System.out.println("执行test方法String类型:" + string);
}
public static void main(String[] args){
Test t = new Test();
t.test('a');//重载方法中没有char类型,自动转换为int类型
}
}
4、JDK1.5版本之后出现动态参数列表
- 类型固定 个数任意(0----n)
- int…x 本质上是一个数组 具有length,[index]等属性
- 动态参数不能与数组类型的方法构成重载
- 动态参数列表在方法中只能有一份,并且只能放在方法参数末尾
- 可以不传参数,相当于0
public class Test {
public void test(int...x){//本质是数组 int[] x = {1,2,3,4,5}
System.out.println("执行test方法动态参数列表");
for(int i=0;i<x.length;i++){
System.out.println(x[i]);
}
}
public void test(){
System.out.println("执行test方法没有参数:");
}
public static void main(String[] args){
Test t = new Test();
t.test();//不传参数时没有参数的test
}
}