- 1.方法重载发生在同一个类中。
- 2.方法名相同。
- 3.参数个数不同 。
- 4.或者 相同个数 类型不同。
- 5.或者 相同个数 不同类型 位置不同。
方法的重载和返回值类型无关,只与类,方法名,参数有关
重载可以减轻编程人员负担。
public class Demo0323 {
public static void main(String[] args) {
int a = 1921;
int b = 28;
int c = 29;
String s1 = "1921";
String s2 = "28";
System.out.println(a + "+" + b + "=" + add(a,b)); //调用重载方法add
System.out.println(s1 + "+" + s2 + "=" + add(s1,s2));
System.out.println("s1+s2=" +s1 + s2); //字符串连接
//System.out.println(s1+"+"+a+"="+add(s1,a)); //出现错误提示
System.out.println(a+"+"+b+"+"+c+"="+add(a, b, c));
}
//重载方法add()
//该方法有两个int类型的形参
public static int add(int a, int b) {
return a + b;
}
//该方法有两个String类型的形参
public static int add(String a,String b) {
int x = Integer.parseInt(a);
int y = Integer.parseInt(b);
return x+y;
}
//该方法有三个int类型的形参
public static int add(int a, int b, int c){
return a + b + c;
}
}