从零开始学Java(打卡第27天)

目标开发一款自己喜欢且能最大限度让用户参与建设的社交软件。(一周没打卡,是否忘记了当初是多么的信誓旦旦——别让未来的自己后悔——请继续打卡)

 笔记:

方法重载(OveryLoad):java中允许同一个类中,多个同名方法的存在,但要求形参列表不一致

 好处:减轻了起名的麻烦,同时减轻了记名的麻烦

public class OverLoad {
	public static void main(String[] args) {
		MyCalculator mc = new MyCalculator();
		System.out.println(mc.calculator(1, 2));
		System.out.println(mc.calculator(1.1, 2));
	}
}

class MyCalculator {
	public int calculator(int n1, int n2) {
		return n1 + n2;
	}public double calculator(int n1, double n2) {
		return n1 + n2;
	}public double calculator(double n1, int n2) {
		return n1 + n2;
	}public int calculator(int n1, int n2, int n3) {
		return n1 + n2 + n3;
	}
}

 注意事项和使用细节:

方法名:必须相同;

形参列表:必须不同(形参类型或个数或顺序,至少有一样不同,参数名无要求);

返回类型:无要求;

 

public class OverLoad {
	public static void main(String[] args) {
		Methods mc = new Methods();
		mc.m(10);
		mc.m(10, 20);
		mc.m("kinssun");
	}
}

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);
	}
}
public class OverLoad {
	public static void main(String[] args) {
		Methods mc = new Methods();
		System.out.println(mc.max(10, 20)); 
		System.out.println(mc.max(6.3, 4.1)); 
		System.out.println(mc.max(12.1, 15.7, 79.3)); 
	}
}

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 max1 = n1 > n2 ? n1 : n2;
		return max1 > n3 ? max1 : n3;
	}
}

可变参数:java允许将同一个类中多个同名同功能但参数个数不同的方法,封装成一个方法。

 基本语法:   访问修饰符   返回类型   方法名 (数据类型...  形参名)

public class VarParameter {
	public static void main(String[] args) {
		Methods m = new Methods();
		System.out.println(m.sum(1, 5, 19));
		System.out.println(m.sum(78, 21, 13));
	}
}

class Methods {
	public int sum(int... nums) {
		int res = 0;
		for (int i = 0; i < nums.length; i++) {
			res += nums[i];
		}
		return res;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值