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

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):
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)
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)
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.

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 ≤ i ≤ n, 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.

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.

So, it is pretty simple:
1) Yes, the decision is made at compile-time. The compiler chooses the method with the most specific matching type. So the compiler will choose the Number version when the variable you pass as an argument is declared as a Number, even if it is an Integer at run-time. (If the compiler finds two "equally matching" methods, an ambiguous method error will make the compilation fail)
2) At run-time, there are no generics, everything is just an Object. Generics are a compile-time and source-code feature only. Therefore the compiler must do the best he can, because the VM surely can not.

Related

Multiple constructors with variable argument parameters

Given these two constructors:
SomeClass(int... params)
{
// Do things
}
SomeClass(long... otherParams)
{
// Do other things
}
What happens when an object foo is instantiated?
SomeClass foo = new SomeClass();
Is the undefined default constructor somehow called? Or is one of those constructors with an empty array called? If so, what’s the precedent?
I’ve done some basic testing and found that if a constructor without parameters is defined then that will be called. Otherwise, it appears that an ambiguous one is called.
As per this very good answer in "Varargs in method overloading in Java" question below are the rules used by Java compiler for selecting the method signature to invoke. They are based on JLS 5.3. Method Invocation Conversion docs.
Primitive widening uses the smallest method argument possible
Wrapper type cannot be widened to another Wrapper type
You can Box from int to Integer and widen to Object but no to Long
Widening beats Boxing, Boxing beats Var-args.
You can Box and then Widen (An int can become Object via Integer)
You cannot Widen and then Box (An int cannot become Long)
You cannot combine var-args, with either widening or boxing
Because both constructors are var-args (rule 7) the compiler will fall back to other rules and select the method that uses the smallest type (rule 1).
You can confirm this behaviour with following code:
static class SomeClass {
SomeClass(long... value) { System.out.println("Long"); }
SomeClass(int... value) { System.out.println("Int"); }
SomeClass(byte... value) { System.out.println("Byte"); }
}
public static void main(String[] args) throws Exception {
SomeClass o = new SomeClass(); // Byte
}
The precise subtype relation between primitives types used in rule 1 is explained in JLS 4.10.1. Subtyping among Primitive Types.
The following rules define the direct supertype relation among the primitive types:
double >1 float
float >1 long
long >1 int
int >1 char
int >1 short
short >1 byte
Only classes without any explicit constructors at all get a default constructor. For a class that does have one or more constructors explicitly defined, their arity, variable or not, has no bearing. Thus it is reasonably common for a class to have no nullary constructor, and that is in fact the case of your class.
Choosing from among multiple available constructors works the same way as choosing among overloaded methods. First, the available constructors are determined. Then, those that are applicable to the given arguments are identified. Finally, the most specific among the applicable constructors is selected. Details are specified in section 15.12 of JLS10. It is a compile-time error if that process does not result in identifying exactly one constructor.
In your example, both available constructors are applicable to an empty argument list, so it comes down to a question of choosing the most specific. The JLS provides an informal description:
one method is more specific than another if any invocation handled by
the first method could be passed on to the other one without a
compile-time error.
The formal rules revolve around the types of the formal parameters, and account for formal type / subtype relationships among primitive types, with the end result that SomeClass(int...) is more specific than SomeClass(long...) when both are applicable. The former, then, is the one chosen in your example.

Which of the overloaded methods will be called on runtime if we apply type erasure, and why?

Suppose we have the following generic class
public class SomeType<T> {
public <E> void test(Collection<E> collection){
System.out.println("1st method");
for (E e : collection){
System.out.println(e);
}
}
public void test(List<Integer> integerList){
System.out.println("2nd method");
for (Integer integer : integerList){
System.out.println(integer);
}
}
}
Now inside main method we have the following code snippet
SomeType someType = new SomeType();
List<String> list = Arrays.asList("value");
someType.test(list);
As a result of executing someType.test(list) we will get "2nd method" in our console as well as java.lang.ClassCastException. As I understand, the reason of why second test method being executed is that we don't use generics for SomeType. So, compiler instantly removes all generics information from the class (i.e. both <T> and <E>). After doing that second test method will have List integerList as a parameter and of course List matches better to List than to Collection.
Now consider that inside main method we have the following code snippet
SomeType<?> someType = new SomeType<>();
List<String> list = Arrays.asList("value");
someType.test(list);
In this case we will get "1st method" in the console. It means that first test method being executed. The question is why?
From my understanding on runtime we never have any generics information because of type erasure. So, why then second test method cannot be executed. For me second test method should be (on runtime) in the following form public void test(List<Integer> integerList){...} Isn't it?
Applicable methods are matched before type erasure (see JSL 15.12.2.3). (Erasure means that runtime types are not parameterized, but the method was chosen at compile time, when type parameters were available)
The type of list is List<String>, therefore:
test(Collection<E>) is applicable, because List<Integer> is compatible with Collection<E>, where E is Integer (formally, the constraint formula List<Integer> → Collection<E> [E:=Integer] reduces to true, because List<Integer> is a subtype of Collection<Integer>).
test(List<String>) is not applicable, because List<String> is not compatible with List<Integer> (formally, the constraint formula List<String> → List<Integer> reduces to false because String is not a supertype of Integer).
The details are explained hidden in JSL 18.5.1.
For test(Collection<E>):
Let θ be the substitution [E:=Integer]
[...]
A set of constraint formulas, C, is constructed as follows: let F1, ..., Fn be the formal parameter types of m, and let e1, ..., ek be the actual argument expressions of the invocation.
In this case, we have F1 = Collection<E> and e1 = List<Integer>
Then: [the set of constraint formulas] includes ‹ei → Fi θ›
In this case, we have List<Integer> → Collection<E> [E:=Integer] (where → means that e1 is compatible with F1 after the type-variable E has been inferred)
For test(List<String>), there is no substitution (because there are no inference variables) and the constraint is just List<String> → List<Integer>.
The JLS is a bit of a rat's nest on this one, but there is an informal (their words, not mine) rule that you can use:
[O]ne method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time error.
For the sake of argument, let's call <E> test(Collection<E>) method 1, and test(List<Integer>) method 2.
Let's throw a spanner in here - we know that this entire class is generic, so instantiation of it without a type of some kind produces... less than desirable type checks at runtime.
The other part to this is due to the fact that List is more specific than Collection, if a method is passed a List, it will seek to accommodate that more readily than a Collection, with the caveat that the type should be checked at compile time. Since it isn't with that raw type, I believe that this particular check is skipped, and Java is treating List<Integer> as more specific than Collection<capture(String)>.
You should file a bug with the JVM, since this appears to be inconsistent. Or, at least, have the folks who penned the JLS explain why this is legal in slightly better English than their wonky math notation...
Moving on; with your second example, you give us the courtesy of typing your instance as a wildcard, which allows Java to make the correct compile-time assertion that test(Collection<E>) is the safest method to choose.
Note that none of these checks happen at runtime. These are all decisions made before Java runs, as ambiguous method calls or a call to a method with an unsupported parameter results in a compile time error.
Moral of the story: don't use raw types. They're evil. It makes the type system behave in strange ways, and it's really only there to maintain backwards compatibility.

Why does the Java 8 generic type inference pick this overload?

Consider the following program:
public class GenericTypeInference {
public static void main(String[] args) {
print(new SillyGenericWrapper().get());
}
private static void print(Object object) {
System.out.println("Object");
}
private static void print(String string) {
System.out.println("String");
}
public static class SillyGenericWrapper {
public <T> T get() {
return null;
}
}
}
It prints "String" under Java 8 and "Object" under Java 7.
I would have expected this to be an ambiguity in Java 8, because both overloaded methods match. Why does the compiler pick print(String) after JEP 101?
Justified or not, this breaks backward compatibility and the change cannot be detected at compile time. The code just sneakily behaves differently after upgrading to Java 8.
NOTE: The SillyGenericWrapper is named "silly" for a reason. I'm trying to understand why the compiler behaves the way it does, don't tell me that the silly wrapper is a bad design in the first place.
UPDATE: I've also tried to compile and run the example under Java 8 but using a Java 7 language level. The behavior was consistent with Java 7. That was expected, but I still felt the need to verify.
The rules of type inference have received a significant overhaul in Java 8; most notably target type inference has been much improved. So, whereas before Java 8 the method argument site did not receive any inference, defaulting to Object, in Java 8 the most specific applicable type is inferred, in this case String. The JLS for Java 8 introduced a new chapter Chapter 18. Type Inference that's missing in JLS for Java 7.
Earlier versions of JDK 1.8 (up until 1.8.0_25) had a bug related to overloaded methods resolution when the compiler successfully compiled code which according to JLS should have produced ambiguity error Why is this method overloading ambiguous? As Marco13 points out in the comments
This part of the JLS is probably the most complicated one
which explains the bugs in earlier versions of JDK 1.8 and also the compatibility issue that you see.
As shown in the example from the Java Tutoral (Type Inference)
Consider the following method:
void processStringList(List<String> stringList) {
// process stringList
}
Suppose you want to invoke the method processStringList with an empty list. In Java SE 7, the following statement does not compile:
processStringList(Collections.emptyList());
The Java SE 7 compiler generates an error message similar to the following:
List<Object> cannot be converted to List<String>
The compiler requires a value for the type argument T so it starts with the value Object. Consequently, the invocation of Collections.emptyList returns a value of type List, which is incompatible with the method processStringList. Thus, in Java SE 7, you must specify the value of the value of the type argument as follows:
processStringList(Collections.<String>emptyList());
This is no longer necessary in Java SE 8. The notion of what is a target type has been expanded to include method arguments, such as the argument to the method processStringList. In this case, processStringList requires an argument of type List
Collections.emptyList() is a generic method similar to the get() method from the question. In Java 7 the print(String string) method is not even applicable to the method invocation thus it doesn't take part in the overload resolution process. Whereas in Java 8 both methods are applicable.
This incompatibility is worth mentioning in the Compatibility Guide for JDK 8.
You can check out my answer for a similar question related to overloaded methods resolution Method overload ambiguity with Java 8 ternary conditional and unboxed primitives
According to JLS 15.12.2.5 Choosing the Most Specific Method:
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.
Then:
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 ≤ i ≤ n, n = k).
m2 is not generic, and m1 and m2 are applicable by variable arity
invocation, and where the first k variable arity parameter types of m1
are S1, ..., Sk and the first k variable arity parameter types of m2
are T1, ..., Tk, the type Si is more specific than Ti for argument ei
for all i (1 ≤ i ≤ k). Additionally, if m2 has k+1 parameters, then
the k+1'th variable arity parameter type of m1 is a subtype of the
k+1'th variable arity parameter type of m2.
The above conditions are the only circumstances under which one method may be more specific than another.
A type S is more specific than a type T for any expression if S <: T (§4.10).
The second of three options matches our case. Since String is a subtype of Object (String <: Object) it is more specific. Thus the method itself is more specific. Following the JLS this method is also strictly more specific and most specific and is chosen by the compiler.
In java7, expressions are interpreted from bottom up (with very few exceptions); the meaning of a sub-expression is kind of "context free". For a method invocation, the types of the arguments are resolved fist; the compiler then uses that information to resolve the meaning of the invocation, for example, to pick a winner among applicable overloaded methods.
In java8, that philosophy does not work anymore, because we expect to use implicit lambda (like x->foo(x)) everywhere; the lambda parameter types are not specified and must be inferred from context. That means, for method invocations, sometimes the method parameter types decide the argument types.
Obviously there's a dilemma if the method is overloaded. Therefore in some cases, it's necessary to resolve method overloading first to pick one winner, before compiling the arguments.
That is a major shift; and some old code like yours will fall victim to incompatibility.
A workaround is to provide a "target typing" to the argument with "casting context"
print( (Object)new SillyGenericWrapper().get() );
or like #Holger's suggestion, provide type parameter <Object>get() to avoid inference all together.
Java method overloading is extremely complicated; the benefit of the complexity is dubious. Remember, overloading is never a necessity - if they are different methods, you can give them different names.
First of all it has nothing to do with overriding , but it has to deal with overloading.
Jls,. Section 15 provides lot of information on how exactly compiler selects the overloaded method
The most specific method is chosen at compile time; its descriptor
determines what method is actually executed at run time.
So when invoking
print(new SillyGenericWrapper().get());
The compiler choose String version over Object because print method that takes String is more specific then the one that takes Object. If there was Integer instead of String then it will get selected.
Moreover if you want to invoke method that takes Object as a parameter then you can assign the return value to the parameter of type object E.g.
public class GenericTypeInference {
public static void main(String[] args) {
final SillyGenericWrapper sillyGenericWrapper = new SillyGenericWrapper();
final Object o = sillyGenericWrapper.get();
print(o);
print(sillyGenericWrapper.get());
}
private static void print(Object object) {
System.out.println("Object");
}
private static void print(Integer integer) {
System.out.println("Integer");
}
public static class SillyGenericWrapper {
public <T> T get() {
return null;
}
}
}
It outputs
Object
Integer
The situation starts to become interesting when let say you have 2 valid method definations that are eligible for overloading. E.g.
private static void print(Integer integer) {
System.out.println("Integer");
}
private static void print(String integer) {
System.out.println("String");
}
and now if you invoke
print(sillyGenericWrapper.get());
The compiler will have 2 valid method definition to choose from , Hence you will get compilation error because it cannot give preference to one method over the other.
I ran it using Java 1.8.0_40 and got "Object".
If you'll run the following code:
public class GenericTypeInference {
private static final String fmt = "%24s: %s%n";
public static void main(String[] args) {
print(new SillyGenericWrapper().get());
Method[] allMethods = SillyGenericWrapper.class.getDeclaredMethods();
for (Method m : allMethods) {
System.out.format("%s%n", m.toGenericString());
System.out.format(fmt, "ReturnType", m.getReturnType());
System.out.format(fmt, "GenericReturnType", m.getGenericReturnType());
}
private static void print(Object object) {
System.out.println("Object");
}
private static void print(String string) {
System.out.println("String");
}
public static class SillyGenericWrapper {
public <T> T get() {
return null;
}
}
}
You will see that you get:
Object public T
com.xxx.GenericTypeInference$SillyGenericWrapper.get()
ReturnType: class java.lang.Object
GenericReturnType: T
Which explains why the method overloaded with Object is used and not the String one.

Compiler error : reference to call ambiguous

Case 1
static void call(Integer i) {
System.out.println("hi" + i);
}
static void call(int i) {
System.out.println("hello" + i);
}
public static void main(String... args) {
call(10);
}
Output of Case 1 : hello10
Case 2
static void call(Integer... i) {
System.out.println("hi" + i);
}
static void call(int... i) {
System.out.println("hello" + i);
}
public static void main(String... args) {
call(10);
}
Shows compilation error reference to call ambiguous. But, I was unable to understand. Why ? But, when I commented out any of the call() methods from Case 2, then It works fine. Can anyone help me to understand, what is happening here ?
Finding the most specific method is defined in a very formal way in the Java Language Specificaion (JLS). I have extracted below the main items that apply while trying to remove the formal formulae as much as possible.
In summary the main items that apply to your questions are:
JLS 15.12.2: your use case falls under phase 3:
The third phase (§15.12.2.4) allows overloading to be combined with variable arity methods, boxing, and unboxing.
Then JLS 15.12.2.4 basically determines that both method are applicable, because 10 can be converted to both an Integer... or an int.... So far so good. And the paragraph concludes:
The most specific method (§15.12.2.5) is chosen among the applicable variable-arity methods.
Which brings us to JLS 15.12.2.5. This paragraph gives the conditions under which an arity method m(a...) is more specific than another arity method m(b...). In your use case with one parameter and no generics, it boils down to:
m(a...) is more specific than m(b...) iif a <: b, where <: means is a subtype of.
It happens that int is not a subtype of Integer and Integer is not a subtype of int.
To use the JLS language, both call methods are therefore maximally specific (no method is more specific than the other). In this case, the same paragraph concludes:
If all the maximally specific methods have override-equivalent (§8.4.2) signatures [...] => not your case as no generics are involved and Integer and int are different parameters
Otherwise, we say that the method invocation is ambiguous, and a compile-time error occurs.
NOTE
If you replaced Integer... by long... for example, you would have int <: long and the most specific method would be call(int...)*.
Similarly, if you replaced int... by Number..., the call(Integer...) method would be the most specific.
*There was actually a bug in JDKs prior to Java 7 that would show an ambiguous call in that situation.
Looks like it's related to bug #6886431, which seems to be fixed in OpenJDK 7.
Below is the bug description,
Bug Description:
When invoking a method with the following overloaded signatures, I
expect an ambiguity error (assuming the arguments are compatible with
both):
int f(Object... args);
int f(int... args);
javac treats the second as more specific than the first. This
behavior is sensible (I prefer it), but is inconsistent with the JLS
(15.12.2).
from JLS 15.12.2.2
JLS 15.12.2.2 Choose the Most Specific Method
IIf more than one method declaration 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. The
informal intuition is that one method declaration is more specific
than another if any invocation handled by the first method could be
passed on to the other one without a compile-time type error.
neither of these methods can be passed to the other (the types for int[] and Integer[] arent related) hence the call is ambiguous
The compiler doesn't know which method should be called. In order to fix this, you need to cast the input parameters..
public static void main(String... args) {
call((int)10);
call(new Integer(10));
}
EDIT:
It is because the compiler tries to convert the Integer into int, Therefore, an implicit cast takes place prior to invocation of the call method. So the compiler then looks for any methods by that name that can take ints. And you have 2 of them, so the compiler doesn't know which of both should be called.
If more than one method can be applicable, than from the Java Language Specification we Choosing the Most Specific Method, paragraph 15.12.2.5:
One variable arity member method named m is more specific than another variable arity member method of the same name if either (<: means subtyping):
One member method has n parameters and the other has k parameters, where n ≥ k, and:
The types of the parameters of the first member method are T1, ..., Tn-1, Tn[].
(we have only one T_n[], which is Integer[], n=1)
The types of the parameters of the other method are U1, ..., Uk-1, Uk[]. (again only one paramenter, which is int[], k=1)
If the second method is generic then let R1 ... Rp (p ≥ 1) be its type parameters, let Bl be the declared bound of Rl (1 ≤ l ≤ p), let A1 ... Ap be the type arguments inferred (§15.12.2.7) for this invocation under the initial constraints Ti << Ui (1 ≤ i ≤ k-1) and Ti << Uk (k ≤ i ≤ n), and let Si = Ui[R1=A1,...,Rp=Ap] (1 ≤ i ≤ k). (method is not generic)
Otherwise, let Si = Ui (1 ≤ i ≤ k). (S1 = int[])
For all j from 1 to k-1, Tj <: Sj, and, (nothing here)
For all j from k to n, Tj <: Sk, and, (Compare T1 <: S1, Integer[] <: int[])
If the second method is a generic method as described above, then Al <: Bl[R1=A1,...,Rp=Ap] (1 ≤ l ≤ p). (method is not generic)
Although primitive int is autoboxed to wrapper Integer, int[] is not autoboxed to Integer[], than the first condition doesn't hold.
Second condition is almost the same.
There are also other conditions that do not hold, and then due to JLS:
we say that the method invocation is ambiguous, and a compile-time error occurs.
This question has already been asked a number of times. The tricky part is that f(1, 2, 3) is clearly passing int's, so why can't the compiler pick the f(int...) version? The answer must lie somewhere in the JLS, which I'm scratching my heads against
According to §15.12.2.4, both methods are applicable variable-arity method, so the next step is identifying the most specific one.
Unofortunately, §15.12.2.5 uses the subtype test Ti <: Si between f1(T1, .. Tn) and f2(S1, .. Sn) formal parameters to identify the target method, and since there is no subtype relationship between Integer and int, no one wins, because neither int :> Integer nor Integer :> int. At the end of the paragraph is stated:
The above conditions are the only circumstances under which one method
may be more specific than another. [...]
A method m1 is strictly more specific than another method m2 if
and only if m1 is more specific than m2 and m2 is not more specific
than m1.
A method is said to be maximally specific for a method invocation
if it is accessible and applicable and there is no other method that
is applicable and accessible that is strictly more specific.
It is possible that no method is the most specific, because there are
two or more methods that are maximally specific. In this case:
[...]
Otherwise, we say that the method invocation is ambiguous, and a compile-time error occurs.
Attached a blog post by Gilad Bracha (see exhibit 2), in turn linked in the bug report from the #Jayamhona's answer.

Is the JLS complete regaring method overriding and generics?

So, I was trying to write a method to answer one of my previous questions: How can I find out if an arbitrary java.lang.Method overrides another one? To do that, I was reading through the JLS, and there are some parts that seem to be missing in one case.
Imagine you have the following classes:
public class A<T> {
public void foo(T param){};
}
public class B extends A<String> {
public void foo(String param){};
}
In this case, it is quite obvious that B.foo overrides A.foo, however I don't understand how this case fits the specification.
Regarding method overriding, the JLS §8.4.8.1 states:
An instance method m1, declared in class C, overrides another instance method m2, declared in class A iff all of the following are true:
C is a subclass of A.
The signature of m1 is a subsignature (§8.4.2) of the signature of m2.
Either:
m2 is public, protected, or declared with default access in the same package as C,or
m1 overrides a method m3 (m3 distinct from m1, m3 distinct from m2), such that m3 overrides m2.
Obviously points 1 and 3 are satisfied in our case. Let's look a bit deeper in the JLS what subsignature means. The JLS §8.4.2 says:
Two methods have the same signature if they have the same name and argument types.
Two method or constructor declarations M and N have the same argument types if all of the following conditions hold:
They have the same number of formal parameters (possibly zero)
They have the same number of type parameters (possibly zero)
Let A1, ..., An be the type parameters of M and let B1, ..., Bn be the type parameters of N. After renaming each occurrence of a Bi in N's type to Ai, the bounds of corresponding type variables are the same, and the formal parameter types of M and N are the same.
In our case, point 1 is clearly true (both have 1 argument).
Point 2 is a bit more muddy (and that's where I'm not sure what the spec means exactly): Neither of the methods declare their own type parameters, but A.foo uses T which is a type variable that paramterizes the class.
So my first question is: in this context, do Type variables declared in the class count or not?
Ok, now let's assume that T doesn't count and that therefore point 2 is false (I don't know how I could even apply point 3 in this case). Our two methods do not have the same signature, but that doesn't prevent B.foo from being a subsignature of A.foo.
A little further in JLS §8.4.2 it says:
The signature of a method m1 is a subsignature of the signature of a method m2 if either:
m2 has the same signature as m1, or
the signature of m1 is the same as the erasure (§4.6) of the signature of m2.
We have already determined that point 1 is false.
The erasure signature of a method according to JLS §4.6 is a signature consisting of the same name as s and the erasures of all the formal parameter types given in s. So the erasure of A.foo is foo(Object) and the erasure of B.foo is foo(String). These two are different signatures, therefore point 2 is also false, and B.foo is not a subsignature of A.foo, and therefore B.foo does not override A.foo.
Except it does...
What am I missing? Is there some piece of the puzzle that I'm not seeing, or is the spec really not complete in this case?
do Type variables declared in the class count or not?
The elements in question are the methods, not the containing type declarations. So, no, they don't count.
Ok, now let's assume that T doesn't count and that therefore point 2 is false
Why? They both have 0 type parameters, so it's true.
Step by step:
They have the same number of formal parameters (possibly zero)
Both methods have 1 formal parameter. Check.
They have the same number of type parameters (possibly zero)
Neither method declares a type parameter. Check.
Let A1, ..., An be the type parameters of M and let B1, ..., Bn be the type parameters of N. After renaming each occurrence of a Bi in N's type to Ai, the bounds of corresponding type variables are the same, and the formal parameter types of M and N are the same.
Since neither method declares a type parameter there's nothing to rename and the formal parameter types are the same -- T[T=String] = String. Check.
⇒ B.foo(String) has the same signature as A<String>.foo(String).
⇒ B.foo(String) is a subsignature of A<String>.foo(String)
Since B is a subclass of A and A<String>.foo(String) is public we can conclude B.foo(String) overrides A<String>.foo(String).
You must look at it this way:
The class B extends the type A<String>, which has a method foo(String param).
A<String> is an invocation of the generic type A<T>. It is a type in its own right. This is implied by JLS 4.5, which defines what a parameterized type is. A<String> is a parameterized type and is on equal footing with any other reference type. The fact that it is parameterized is not important when discussing the concept of the direct superclass.
Excerpt from Oracle's tutorial on generics:
After type erasure, the method signatures do not not match. The Node method becomes setData(Object) and the MyNode method becomes setData(Integer). Therefore, the MyNode setData method does not override the Node setData method.
To solve this problem and preserve the polymorphism of generic types after type erasure, a Java compiler generates a bridge method to ensure that subtyping works as expected.
So basically, compiler magic makes your compiled code work as expected, even with the JLS as it is. I'm not sure where this behavior is specified.

Categories

Resources