总的来说,尽可能考虑多种情况。
比方说:明天周末,你要准备好明天与女朋友的活动计划,要适时而定,不同情况要有不同安排。明天下雨的话,待在家里打电动玩吃鸡;明天阳光晴朗,考虑去公园游乐场之类的。
回到正题:一个类中可以有很多方法具有相同名字,但是方法的参数必须不同:
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)调用时无法编译,因为他不确定到底是哪一个方法。