javaoverloadingboxing

Why does invoking a method with a short choose the `void (int)` overload over `void (Short)`?


I am learning Java. When I call go(x), I get ‘int’. Why not ‘Short’?

public class test {
    public static void go(Short n) {System.out.println("Short");}
    public static void go(int n) {System.out.println("int");}
    
    public static void main(String[] args) {
        short x=11;
        go(x);
    }
}

Solution

  • When you make a call to an overloaded method, the compiler needs to decide statically which of the overloads will be called. Intuitively, this is done by looking at each of the overloads' signatures, and working out which one is the best match ... based on the static types of the argument expressions. If there is a tie (i.e. no single "best" match), the compiler gives an error saying that the method call is ambiguous.

    This is the code of your example.

    public class test {
        public static void go(Short n) {System.out.println("Short");}
        public static void go(int n) {System.out.println("int");}
        
        public static void main(String[] args) {
            short x=11;
            go(x);
        }
    }
    

    The reason that this prints "int" rather than "Short" is because go(int) is deemed to be a better match than go(Short) to a call where the argument expression's static type is short.

    (Technically, short is a subtype of int, but not of Short.)

    If we change your code to this:

    public class test {
        public static void go(short n) {System.out.println("short");}
        public static void go(int n) {System.out.println("int");}
        
        public static void main(String[] args) {
            short x=11;
            go(x);
        }
    }
    

    we will now see that short is printed. The type short is a subtype1 of both short and int, but go(short) is a closer match than go(int).

    The relevant section of the Java Language Specification is JLS 15.2. But beware that is long and complicated ... and NOT recommended for beginners to try to read. (Indeed, I would posit that most Java programmers don't fully understand all of what it says. Myself included!)


    1 - This is according to the definition of subtype used in the JLS.