The relationship of overload and method return type in Java?

前端 未结 4 1161
-上瘾入骨i
-上瘾入骨i 2020-12-06 21:04

If there are two methods, they have different parameters, and their return types are different. Like this:

int test(int p) {
   System.out.p         


        
4条回答
  •  攒了一身酷
    2020-12-06 21:38

    Yes, this is also an overload. Since only the name and the list of parameters are considered part of method's signature for the purposes of method overloading, both your test methods are overloads of each other.

    There may be useful scenarios for overloading a method like that, too. Consider this example:

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

    A programmer who uses Sanitizer can write things like

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

    and the overload makes the code looks the same for variables of different types.

提交回复
热议问题