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);
}
}
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.
The reason that this prints "int" rather than "Short" is because
go(int)is deemed to be a better match thango(Short)to a call where the argument expression's static type isshort.(Technically,
shortis a subtype ofint, but not ofShort.)If we change your code to this:
we will now see that
shortis printed. The typeshortis a subtype1 of bothshortandint, butgo(short)is a closer match thango(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.