Java基础 4.15

1.重载方法练习

/*
类Methods中定义三个重载方法并调用 方法名为m
分别接受一个int参数 两个int参数 一个字符串参数 
分别执行平方运算并输出 相乘并输出结果 输出字符串信息
在main()方法中分别用参数区别调用三个方法
*/
public class OverLoadExercise01 {
	public static void main(String[] args) {
		Methods myMethods = new Methods();
		int n1 = myMethods.m(5);
		int n2 = myMethods.m(6, 8);
		myMethods.m("你是谁?");
		System.out.println(n1);
		System.out.println(n2);

	}
}

class Methods {
	public int m(int n1) {
		return n1 * n1;
	}

	public int m(int n1, int n2) {
		return n1 * n2;
	}

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

/*
在Methods类 定义三个重载方法max(),第一个方法,返回两个int值中最大值
第二个方法,返回两个double值中的最大值,第三个方法,返回三个double值中的最大值
并分别调用三个方法
*/
public class OverLoadExercise02 {
	public static void main(String[] args) {
		Methods methods =  new Methods();
		System.out.println(methods.max(2, 3));
		System.out.println(methods.max(2.2, 8.8));
		System.out.println(methods.max(123.23, 123.67, 123.4634));
	}
}

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 n1, double n2, double n3) {
		double max = n1 > n2 ? n1 : n2;
		return max > n3 ? max : n3;		
	}
}

 

tips:

若有

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

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

以上仍构成重载 只是输入的值可以自动转换 

若输入为(60.0, 20) 优先返回无需转换的max(double n1, int n2)

若输入为(60.0, 20.0)则也可直接返回对应max(double n1, double n2)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值