Java method specificity

149 views Asked by At

I'm trying to understand how Java picks among overloaded methods, and I found JLS 15.12.2.5 Choosing the Most Specific Method

I wrote the below to test my understanding

public class Foo {
  static <T> T f(T x) {
    System.err.println("T " + x);
    return x;
  }
  static <T> T f(CharSequence x) {
    System.err.println("CharSequence " + x);
    return null;
  }
  public static void main(String... argv) {
    CharSequence c = "c";
    String s = "s";
    Foo.f(c);          // Prints "CharSequence c"
    Foo.f(s);          // Prints "CharSequence s"
    Foo.<String>f(s);  // Prints "CharSequence s".  Why???
  }
}

I was surprised by the Foo.<String>f(s) call. My naive understanding of specificity was that, after template parameter substitution, Foo.<String>f(s), applied to the two overloads of f gives f(String) and f(CharSequence) of which the first is more specific.

Section 15.12 is a bit hard to grok, but it looks like the operative part is

  • m2 is generic, and m1 is inferred to be more specific than m2 for argument expressions e1, ..., ek by ยง18.5.4.

and the type parameter bindings are not taken into account for the purposes of specificity.

Is that the case? Can anyone explain inferred to be more specific than in plain language?

0

There are 0 answers