方法重载OverLoad

方法重载(OverLoad

基本介绍:

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

比如:System.out.println(); outPrintStream类型

重载的好处:

  1. 减轻了起名的麻烦
  2. 减轻了记名的麻烦

重载:方法名相同;参数列表不同;与返回值类型无关

2.方法重载快速入门案例

案例:类MyCalculate(计算器)
calculate(int n1,int n2);
calculate(int n1,double n2);
calculate(double n1,int n2);
calculate(int n1,int n2,int n3);
package OverLoad_方法重载;

public class OverLoad01 {
    public static void main(String[] args) {
        myCalculate calculate = new myCalculate();
        int calculate1 = calculate.calculate(1, 1, 2);
        System.out.println(calculate1);
    }
}
/**
 *   案例:类MyCalculate(计算器)
 * calculate(int n1,int n2);
 * calculate(int n1,double n2);
 * calculate(double n1,int n2);
 * calculate(int n1,int n2,int n3);
 */
class myCalculate{
   public int  calculate(int n1,int n2){
       return n1 + n2;
   }

   public double calculate(int n1,double n2){
       return n1 + n2;
    }
   public double calculate(double n1,int 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方法中分别用参数区别调用三个方法
2.定义三个重载方法max(),第一个方法,返回两个int值中的最大值,第二个方法返回两个double值中的最大值,第三个方法返回三个double值中的最大值,并分别调用这三个方法
package OverLoad_方法重载;

public class OverLoadExercise {
    public static void main(String[] args) {
        Methods methods = new Methods();
        int m = methods.m(8);
        methods.m(4,3);
        methods.m("我会牢牢记住你的脸!");
        System.out.println("=============================");

        double max = methods.max(11, 88, 3);
        System.out.println(max);
    }
}
class Methods{
    public int m(int n){
        int result = n*n;
        System.out.println("平方运算的结果:result="+result);
        return result;
    }

    public void m(int n1,int n2){
        int result = n1*n2;
        System.out.println("两个数相乘的结果:result="+result);
    }

    public void m(String str){
        System.out.println(str);
    }

    public int max(int n1,int n2){
        return n1 >= n2 ? n1 : n2;
    }

    public double max(double n1,int n2){
        return n1 >= n2 ? n1 : n2;
    }

    public double max(double n1,double n2,double n3){
//       if (n1<=n2){
//           n1=n2;
//       }
//       if (n1<=n3){
//            n1=n3;
//       }
//       return n1;
      double max;
      max = n1 >= n2 ? n1 : n2;
      return max >= n3 ? max : n3;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值