Java基础28(方法重载)

方法重载

在java中,允许同一个类中存在多个同名方法,但要求它们的形参列表不一致。

重载的好处
1.减轻起名麻烦
2.减轻记名麻烦

入门案例:

规定一个类:MyCalculator,方法:calculate
要求使用同样的方法名实现以下功能:
calculate(int n1,int n2),求两个整数的和
calculate(int n1,double n2),求一个整数,一个double的和
calculate(double n1,int n2),求一个double,一个int的和
calculate(int n1,int n2,int n3),求三个整数的和

代码实现

public static void main(){
   MyCalculator mc = new MyCalculator();
   System.out.println(mc.calculate(1,2));
   System.out.println(mc.calculate(1.1,2));
}

class MyCalculator{
   //两个整数的和
   public int calculate(int n1,int n2){
       System.out.println("两个int的和");
       return n1 + n2;
   }
   //一个整数,一个double的和 
   public double calculate(int n1,double n2){
   	   System.out.println("一个int,一个double的和");
       return n1 + n2;
   }
   //一个double,一个整数的和
   public double calculate(double n1,int n2){
       System.out.println("一个double,个int的和");
       return n1 + n2;
   }
   //三个整数的和
   public int calculate(int n1,int n2,int n3){
       System.out.println("三个int的和");
       return n1 + n2 + n3;
   }
}

Console:
两个int的和
3
一个double,int的和
3.1

总结:
从上面的例子可以看出,重载的方法中形参列表是不同的,而当调用方法时,输入什么类型的实参,就会调用相应的方法,而不是反复调用同一个方法。

方法重载的注意事项

1.方法名必须相同。
2.形参列表必须不同(形参类型或个数或顺序,至少有一项不同,形参名不做规定)

方法重载练习题:

  1. 编写程序,类Methods中定义三个重载方法并调用。方法名为m。并在主类的main方法中分别用参数区别调用三个方法。
    第一个方法:接收一个int参数,执行平方运算并输出结果;
    第二个方法:接收两个int参数,相乘并输出结果;
    第三个方法:接收一个字符串参数,输出字符串信息。

代码实现

pulic class OverLoadExercise{
   public static void main(String[] args){
      Methods method = new Methods();
      method.m(10);//平方
      method.m(10,20);//相乘
      method.m("hello");//输出字符串
   }
}

class Methods{
   public void m(int n){
       System.out.println("平方=" + (n * n));
   }
   public void m(int n1,int n2){
       System.out.println("相乘=" + (n1 * n2));
   }
   public void m(String str){
       System.out.println("传入的str=" + str);
   }
}

Console:
平方=100
相乘=200
传入的str=hello
  1. 在Methods类中,定义三个重载方法max(),并分别调用三个方法。
    第一个方法:返回两个int值中的最大值;
    第二个方法:返回两个double值中的最大值;
    第三个方法:返回三个double值中的最大值;

代码实现

pulic class OverLoadExercise{
   public static void main(String[] args){
      Methods method = new Methods();
      System.out.println(method.max(10,24));
      System.out.println(method.max(10.0,21.4));
      System.out.println(method.max(10.0,1.2,24));
   }
}

class Methods{
    public int max(int n1,int n2){
       return n1 > n2 ? n1 : n2;
    }
    public double max(double n1,double n2){
       return n1 > n2 ? n1 : n2;
    }
    public double max(double m1, double n2, double n3){
       double max1 = n1 > n2 ? n1 : n2;
       return max1 > n3 ? max1 : n3;
    }
}

Console:
24
21.4
24.0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值