Method resolution

Asked

Viewed 55 times

6

in the example below

public static void foo(Integer i) {
    System.out.println("foo(Integer)");
}

public static void foo(short i) {
    System.out.println("foo(short)");
}

public static void foo(long i) {
    System.out.println("foo(long)");
}

public static void foo(int... i) {
    System.out.println("foo(int ...)");
}

public static void main(String[] args) {
    foo(10);
}

foo calls long signature method, because JVM resolves that the closest type of int is long, which is understandable.

he prefers to do this rather than calling the method with Integer signature or int... (array), which would be perfectly compatible.

what is the reason, in terms of language design, for "long" to be more suitable than Integer or int...? Is it expensive for JVM to do this kind of casting internally? (either for int[] or Integer)

1 answer

6


According to the specification of Java, conversion rules are applied so as not to break compatibility with older versions - which did not support autoboxing or methods with variable number of parameters. Thus, it is considered:

  1. One of type conversions for methods, as long as they do not involve autoboxing/autounboxing or a variable number of arguments;
  2. Idem, but now also allowing autoboxing/autounboxing;
  3. Idem, but now also allowing methods with variable number of parameters.

Thus, as during phase 1 an applicable method was found (the one with parameter long) the resolution does not go to phases 2 and 3, so the other options are disregarded. Also by the above rules, if there was no solution in phase 1 the next method to be considered would be the one that receives Integer, and finally what you receive int.... What he receives short is not valid because it implies a more restricted type (narrowing primitive conversions) - which is not applicable in the method call.

  • +1 compatibility. great point, thanks

Browser other questions tagged

You are not signed in. Login or sign up in order to post.