19. 重载的方法能否根据返回值类型进行区分
不能根据返回值进行区分。调用时不指定类型,编译器不知道要用哪个函数。
-
方法签名问题:Java的方法签名是只包含方法名和参数列表,不包含返回值。当编译器解析方法调用时,仅依赖方法名和参数列表来确定,编译器会认为是同一个方法,就会报错。
-
调用歧义问题: 假设允许通过返回值区分,在调用方法时,编译器就不知道通过哪个方法的参数来确定哪个方法
Javaint add(int a, int b); double add(int a, int b);
调用add(1,2) 时,编译器就无法确定
-
Java语言规范: 方法重载必须通过参数列表的不同来区分。返回值类型不能作为区分重载的依据
正确的重载方式:
- 方法名相同
- 参数列表可以不同
- 返回类型可以不同,但不能仅依赖返回类型
Java
public class OverloadExample {
// 方法重载:参数类型不同
public static int add(int a, int b) {
return a + b;
}
public static double add(double a, double b) {
return a + b;
}
// 方法重载:参数数量不同
public static int add(int a, int b, int c) {
return a + b + c;
}
// 方法重载:参数顺序不同
public static int add(int a, double b) {
return (int) (a + b);
}
public static void main(String[] args) {
System.out.println(add(1, 2)); // 调用 int add(int, int)
System.out.println(add(1.5, 2.5)); // 调用 double add(double, double)
System.out.println(add(1, 2, 3)); // 调用 int add(int, int, int)
System.out.println(add(1, 2.5)); // 调用 int add(int, double)
}
}