目录
一、方法重载(OverLoad)
Java中允许同一个类中,多个同名方法的存在,但要求形参列表不一致。
重载的好处:减轻了起名的麻烦和记名的麻烦。
示例代码:
public class OverLoad01 {
public static void main(String[] args) {
OverLoads overLoads = new OverLoads();
overLoads.calculate(1,2);
overLoads.calculate(1.1,2);
}
}
class OverLoads{
public int calculate(int n1, int n2){
return n1 + n2;
}
public double calculate(double n1,int n2){
return n1 + n2;
}
public double calculate(int n1,double n2){
return n1 + n2;
}
public int calculate(int n1,int n2,int n3){
return n1 + n2 + n3;
}
}
二、方法重载的注意事项
1、方法名必须相同
2、形参列表必须不同(形参类型或个数或顺序,至少有一样不同,参数名无要求)
3、返回类型无要求
三、相关案例
1、编写程序,类Methods中定义三个重载方法并调用。方法名为m。三个方法分别接收一个int参数、两个int参数、一个字符串参数。分别执行平方运算并输出结果,相乘并输出结果,输出字符串信息。在主类的main )方法中分别用参数区别调用三个方法。
示例代码:
public class OverLoad02 {
public static void main(String[] args) {
Methods methods = new Methods();
methods.m(2);//调用计算平方的方法
methods.m(3,4);//调用计算两数相乘的方法
methods.m("你好,hello");//调用打印字符串的方法
}
}
class Methods{
//计算平方
public void m(int n){
System.out.println("n的平方为:"+(n*n));
}
//计算两个数的结果
public void m(int n1,int n2){
System.out.println("n1乘n2的结果为:"+n1 * n2);
}
//打印字符串信息
public void m(String str){
System.out.println("字符串信息为:"+str);
}
}
2、在Method类,定义三个重载方法max(),第一个万法,返回两个Int中的最大值,第二个方法,返回两个double值中的最大值,第三个方法,返回三个double值中的最大值,并分别调用三个方法。
示例代码:
public class OverLoad03 {
public static void main(String[] args) {
Method method = new Method();
System.out.println("method.max(3,6) = " + method.max(3, 6));//调用判断两个int数的最大值
System.out.println("method.max(4.5,8.9) = " + method.max(4.5, 8.9));//调用判断两个double数的最大值
System.out.println("method.max(4.5,8.9,5.6) = " + method.max(4.5, 8.9, 5.6));//调用判断三个double数的最大值
}
}
class Method{
//判断两个int的最大值
public int max(int n1,int n2){
return n1 > n2 ? n1 : n2;
}
//判断两个double的最大值
public double max(double n1,double n2) {
return n1 > n2 ? n1 : n2;
}
//判断三个double的最大值
public double max(double n1,double n2,double n3){
double max1 = n1 > n2 ? n1 : n2;
return max1 > n3 ? max1 : n3;
}
}