Java学习日记1——方法的重载(overload)

定义:在同一个类中,允许存在一个以上的同名方法,只要它们的参数个数或者参数类型不同即可。
特点:与返回值类型无关,只看参数列表,且参数列表必须不同(参数个数、参数类型或参数顺序不同)。调用时,根据方法参数列表的不同来区别。
示例:
1、判断与void show(int a,char b,double c){}构成重载的有:

  1. void show(int x,char y,double z){} //×
  2. int show(int a,double c,char b){} //√,顺序不同也是重载
  3. void show(int a,double c,char b){} //√
  4. boolean show(int c,char b){} //√
  5. void show(double c){} //√
  6. double show(int x,char y,double z){} //×
  7. 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);
    }
}

B站Java入门编程视频教程P45

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值