Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java method overloading - Generic parameter & parameters within same inheritance tree

Let's assume I have following code:

// Method acception generic parameter
public static <T> T foo(T para) {
    return para;
}

// Method accepting Integer parameter
public static Integer foo(Integer para) {
    return para + 1;
}

// Method accepting Number parameter
public static Number foo(Number para) {
    return para.intValue() + 2;
}

public static void main(String[] args) {
    Float f = new Float(1.0f);
    Integer i = new Integer(1);
    Number n = new Integer(1);
    String s = "Test";

    Number fooedFloat = foo(f);     // Uses foo(Number para)
    Number fooedInteger = foo(i);   // Uses foo(Integer para)
    Number fooedNumber = foo(n);    // Uses foo(Number para)
    String fooedString = foo(s);    // Uses foo(T para)

    System.out.println("foo(f): " + fooedFloat);
    System.out.println("foo(i): " + fooedInteger);
    System.out.println("foo(n): " + fooedNumber);
    System.out.println("foo(s): " + fooedString);
}

The output looks the following:

foo(f): 3
foo(i): 2
foo(n): 3
foo(s): Test

Now the question(s):

  1. foo(n) calls foo(Number para), most probably because n is defined as Number, even though it has an Integer assigned to it. So am I right in the assumption that the decision, which of the overloaded methods is taken happens at compile-time, without dynamic binding? (Question about static and dynamic binding)
  2. foo(f) uses foo(Number para), while foo(i) uses foo(Integer para). Only foo(s) uses the generic version. So the compiler always looks if there is a non-generic implementation for the given types, and only if not it falls back to the generic version? (Question about generics)
  3. Again, foo(f) uses foo(Number para), while foo(i) uses foo(Integer para). Yet, Integer i would also be a Number. So always the method with the "outer-most" type within the inheritance tree is taken? (Question about inheritance)

I know these are a lot questions, and the example is not taken from productive code, yet I just would like to know what "happens behind" and why things happen.

Also any links to the Java documentation or the Java specification are really appreciated, I could not find them myself.

like image 618
Markus Weninger Avatar asked Mar 12 '23 23:03

Markus Weninger


2 Answers

The rules of determining which method signature to call at compile-time are explained in the language specification. Specifically important is the section on choosing the most specific method. Here are the parts related to your questions:

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

...

One applicable method m1 is more specific than another applicable method m2, for an invocation with argument expressions e1, ..., ek, if any of the following are true:

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

  • m2 is not generic, and m1 and m2 are applicable by strict or loose invocation, and where m1 has formal parameter types S1, ..., Sn and m2 has formal parameter types T1, ..., Tn, the type Si is more specific than Ti for argument ei for all i (1 ≤ in, n = k).

...

A type S is more specific than a type T for any expression if S <: T (§4.10).

In this case, Integer is more specific than Number because Integer extends Number, so whenever the compiler detects a call to foo that takes a variable declared of type Integer, it will add an invocation for foo(Integer).

More about the first condition related to the second method being generic is explained in this section. It's a little verbose but I think the important part is:

When testing that one applicable method is more specific than another (§15.12.2.5), where the second method is generic, it is necessary to test whether some instantiation of the second method's type parameters can be inferred to make the first method more specific than the second.

...

Let m1 be the first method and m2 be the second method. Where m2 has type parameters P1, ..., Pp, let α1, ..., αp be inference variables, and let θ be the substitution [P1:=α1, ..., Pp:=αp].

...

The process to determine if m1 is more specific than m2 is as follows:

...

If Ti is a proper type, the result is true if Si is more specific than Ti for ei (§15.12.2.5), and false otherwise. (Note that Si is always a proper type.)

Which basically means that foo(Number) and foo(Integer) are both more specific than foo(T) because the compiler can infer at least one type for the generic method (e.g. Number itself) that makes foo(Number) and foo(Integer) more specific (this is because Integer <: Number and Number <: Number) .

This also means that in your code foo(T) is only applicable (and inherently the most specific method since it's only the one applicable) for the invocation that passes a String.

like image 56
M A Avatar answered Mar 15 '23 23:03

M A


Am I right in the assumption that the decision, which of the overloaded methods is taken happens at compile-time, without dynamic binding?

Yes, Java chooses among available overloads of a method at compile time, based on the declared types of the arguments, from among the alternatives presented by the declared type of the target object.

Dynamic binding applies to choosing among methods having the same signature based on the runtime type of the invocation target. It has nothing directly to do with the runtime types of the actual arguments.

So the compiler always looks if there is a non-generic implementation for the given types, and only if not it falls back to the generic version?

Because of type erasure, the actual signature of your generic method is

Object foo(Object);

Of the argument types you tested, that is the best match among the overloaded options only for the String.

So always the method with the "outer-most" type within the inheritance tree is taken?

More or less. When selecting among overloads, the compiler chooses the alternative that best matches the declared argument types. For a single argument of reference type, this is the method whose argument type is the argument's declared type, or its nearest supertype.

Things can get dicey if Java has to choose among overloads of multiple-argument methods, and it doesn't have an exact match. When there are primitive arguments, it also has to consider the allowed argument conversions. The full details take up a largish section of the JLS.

like image 40
John Bollinger Avatar answered Mar 15 '23 23:03

John Bollinger