方法重载(Java)

总的来说,尽可能考虑多种情况。
比方说:明天周末,你要准备好明天与女朋友的活动计划,要适时而定,不同情况要有不同安排。明天下雨的话,待在家里打电动玩吃鸡;明天阳光晴朗,考虑去公园游乐场之类的。
回到正题:一个类中可以有很多方法具有相同名字,但是方法的参数必须不同
1.参数的个数不停
2.参数个数相同,参数列表的某个参数类型不同

//写一个People类,里面有三个hello方法,展示方法重载。
class People{
	String hello(String a, int b){
		return "Love u,"+a+","+String.valueOf(b);
	}
	String hello(String a ,String b){
            return "U r so "+a+" and "+b;
	}
	String hello(){
            return "I am so into u";
	}
}
//具体实现
public class Relationship{
	public static void main(String arg[]){
		People crush;
                crush = new People();
		System.out.println(crush.hello());
		System.out.println(crush.hello("plmm",3000));
		System.out.println(crush.hello("pretty","cute"));
	}
}

注意:避免歧义

class Dog{
	static void cry(double m , int n){
		System.out.println("小狗");
	}
	static void cry(int m , int n){
		System.out.println("puppy");
}

当Dog.cry(10,10)调用时无法编译,因为他不确定到底是哪一个方法。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值