- Method overloading: In the same class (prerequisite), the method name is the same, the parameter list is different, and the return value is irrelevant.
- Call method overload: JVM decides which method overload to call according to the parameter list
public class User {
//分别写不同名的方法
public int addInt(int a, int b) {
return a + b;
}
public double addDouble(double a, double b) {
return a + b;
}
//使用重载写方法
public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
//整形和浮点型分别用不同的方法
User user = new User();
int sumInt = user.addInt(10, 30);
System.out.println(sumInt);
double sumDouble = user.addDouble(1.2D, 8.8D);
System.out.println(sumDouble);
//调用重载方法
sumInt = user.add(66, 88);
System.out.println(sumInt);
sumDouble = user.add(66.66, 88.88);
System.out.println(sumDouble);
}
}
operation result
40
10.0
154
155.54