定义:在同一个类中,允许存在一个以上的同名方法,只要它们的参数个数或者参数类型不同即可。
特点:与返回值类型无关,只看参数列表,且参数列表必须不同(参数个数、参数类型或参数顺序不同)。调用时,根据方法参数列表的不同来区别。
示例:
1、判断与void show(int a,char b,double c){}构成重载的有:
- void show(int x,char y,double z){} //×
- int show(int a,double c,char b){} //√,顺序不同也是重载
- void show(int a,double c,char b){} //√
- boolean show(int c,char b){} //√
- void show(double c){} //√
- double show(int x,char y,double z){} //×
- void shows(){double c} //×
2、编写程序,定义三个重载方法并调用。方法名为mOL。三个方法分别接收一个int参数、两个int参数、一个字符串参数。分别执行平方运算并输出结果,相乘并输出结果,输出字符串信息。在主类的main ()方法中分别用参数区别调用三个方法。
public class Test{
public static void main(String[] args){
Test tcz2 = new Test();
tcz2.mOL(8);
tcz2.mOL(2,3);
tcz2.mOL("字符串");
}
public void mOL(int i){
System.out.println(i * i);
}
public void mOL(int x, int y){
System.out.println(x * y);
}
public void mOL(String s){
System.out.println(s);
}
}
3、定义三个重载方法max(),第一个方法求两个int值中的最大值,第二个方法求两个double值中的最大值,第三个方法求三个double值中的最大值,并分别调用三个方法。
public class Test {
public static void main(String[] args){
Test tcz3 = new Test();
tcz3.max(2,3);
tcz3.max(2.22,3.33);
tcz3.max(2.22,3.33,4.44);
}
public void max(int x, int y){
if(x >y)
System.out.println("最大值是:" + x);
else{
System.out.println("最大值是:" + y);
}
}
public void max(double x, double y){
double res = 0;
if(x > y)
res = x;
else
res = y;
System.out.println("最大值是:" + res);
}
public void max(double x, double y, double z){
double res = 0;
if(x > y){
if(x > z){
res = x;
}
else{
res = z;
}
}
else{
if(y > z){
res = y;
}
else{
res = z;
}
}
System.out.println("最大值是:" + res);
}
}