Java中重载和方法return类型的关系?

The relationship of overload and method return type in Java?

如果有两个方法,它们有不同的参数,它们的return类型不同。像这样:

int test(int p) {
   System.out.println("version one");
   return p;
}

boolean test(boolean p, int q) {
   System.out.println("version two");
   return p;
}

如果return类型相同,当然这是重载。但是由于 return 类型是 不同的 ,我们是否可以将其视为 overload 仍然?

是的,这也是一个过载。由于出于方法重载的目的,只有名称和参数列表被视为方法签名的一部分,因此您的 test 方法都是彼此的重载。

重载这样的方法也可能有一些有用的场景。考虑这个例子:

class Sanitizer {
    public static String sanitize(String s) {
        ...
    }
    public static int sanitize(int s) {
        ...
    }
    public static double sanitize(double s) {
        ...
    }
}

使用Sanitizer的程序员可以写出类似

的东西
String s2 = Sanitizer.sanitize(s1);
int num2 = Sanitizer.sanitize(num1);

并且重载使得代码对于不同类型的变量看起来相同。

引用the official tutorial:

The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists (there are some qualifications to this that will be discussed in the lesson titled "Interfaces and Inheritance").

具有不同的 return 类型与重载无关紧要。事实上,这在 return 他们的论点之一的方法中很常见。例如,java.util.Math 有一堆重载的 max 方法。两个int的一个max return一个int,两个double的一个max return一个double, 等等

在函数重载中 return 类型不起作用。 函数重载只能通过改变参数来实现。 所以,是的,在你给定的情况下 test() 是超载的

考虑以下几点重载:

  1. 在 java 中重载方法的首要规则是更改方法签名。方法签名由参数数量、参数类型和参数顺序(如果它们属于不同类型)组成。

    public class DemoClass {
        // Overloaded method
        public Integer sum(Integer a, Integer b) {
            return a + b;
        }
    
        // Overloading method
        public Integer sum(Float a, Integer b) {  //Valid
            return null;
        }
    }
    
  2. Return 类型的方法从来不是方法签名的一部分,因此仅更改 return 类型的方法并不等于方法重载。

    public class DemoClass {
        // Overloaded method
        public Integer sum(Integer a, Integer b) {
            return a + b;
        }
    
        // Overloading method
        public Float sum(Integer a, Integer b) {     //Not valid; Compile time error
            return null;
        }
    }
    
  3. 重载方法时也不会考虑方法抛出的异常。所以你的重载方法抛出相同的异常,不同的异常或者它根本不抛出任何异常;对方法加载完全没有影响。

    public class DemoClass {
        // Overloaded method
        public Integer sum(Integer a, Integer b) throws NullPointerException{
            return a + b;
        }
    
        // Overloading method
        public Integer sum(Integer a, Integer b) throws Exception{  //Not valid; Compile time error
            return null;
        }
    }