Why is this method overloading ambiguous? - java

public class Primitive {
void m(Number b, Number ... a) {} // widening, autoboxing->widening->varargs
void m(byte b, Number ... a) {} // unboxing, autoboxing->widening->varargs
public static void main(String[] args) {
Byte b = 12;
Primitive obj = new Primitive();
obj.m(b, 23);
}
}
I have already searched and found that widening priority is higher than unboxing, so in above method invocation, first method should have been called because second parameter is same for both. But this does not happen. Can u plz explain?

It fails to compile in JDK 1.5, 1.6 and 1.7, but works in JDK 1.8.
Update: It seems like the fact that it worked with the first JDK8 versions was actually a bug: It worked in JDK 1.8.0_05, but according to this question and the answer by medvedev1088, this code will no longer compile in 1.8.0_25, which is the behavior that conforms to the JLS
I don't think that this is a bug that was fixed. Instead, it's rather an effect of the changes that are related to the method invocation mechanisms for lambda expressions in Java 8.
Most people would probably agree that the section about "Method Invocation Expressions" is by far the most complex incomprehensible part of the Java Language Specification. And there is probably a whole team of engineers concerned with cross-checking and validating this section. So any statement or any attempted reasoning should be taken with a huge grain of salt. (Even when it comes from the aforementioned engineers). But I'll give it a try, to at least flesh out the relevant parts that others may refer to for a further analysis:
Considering the section about
Method Invocation Expressions in JLS 7
Method Invocation Expressions in JLS 8
and considering that both methods are "Potentially Applicable Methods" ( JLS7 / JLS8 ), then the relevant subsection is the one about
Phase 3: Identify Applicable Variable Arity Methods in JLS7
Phase 3: Identify Methods Applicable by Variable Arity Invocation in JLS8
For JLS 7, it states
The method m is an applicable variable-arity method if and only if all of the following conditions hold:
For 1 = i < n, the type of ei, Ai, can be converted by method invocation conversion to Si.
...
(The other conditions are referring to forms of invocation that are not relevant here, e.g. invocations that really use the varargs, or invocations that involve generics)
Referring to the example: A method is applicable for the actual argument expression b of type Byte when b can be converted to the respective formal method parameter via method invocation conversion. According to the corresponding section about Method Invocation Conversion in JLS7, the following conversions are allowed:
an identity conversion (§5.1.1)
a widening primitive conversion (§5.1.2)
a widening reference conversion (§5.1.5)
a boxing conversion (§5.1.7) optionally followed by widening reference conversion
an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion.
Obviously, there are two methods that are applicable according to this specification:
m(Number b, Number ... a) is applicable via widening reference conversion
m(byte b, Number ... a) is applicable via unboxing conversion
You mentioned that you "...found that widening priority is higher than unboxing", but this is not applicable here: The conditions listed above do not involve any "priority". They are listed as different options. Even if the first method was void m(Byte b, Number ... a), the "identity conversion" would be applicable, but it would still only count as one possible conversion, and cause an error method due to the ambiguity.
So, as far as I understood, this explains why it did not work with JDK7. I did not figure out in detail why it did work with JDK8. But the definition of applicability of variable arity methods changed slighly in Identify Methods Applicable by Variable Arity Invocation in JLS 8:
If m is not a generic method, then m is applicable by variable arity invocation if, for 1 ≤ i ≤ k, either ei is compatible in a loose invocation context with Ti or ei is not pertinent to applicability (§15.12.2.2).
(I did not yet dive deeper into the definitions of "loose invocation contexts" and the section §15.12.2.2, but this seems to be the crucial difference here)
An aside, once more referring to your statement that you "...found that widening priority is higher than unboxing": This is true for methods that do not involve varargs (and that do not require method invocation conversion at all). If you left out the varags in your example, then the process of finding the matching method would start in Phase 1: Identify Matching Arity Methods Applicable by Subtyping. The method m(Number b) would then already be applicable for the parameter Byte b due to Byte being a subtype of Number. There would be no reason to go into Phase 2: Identify Matching Arity Methods Applicable by Method Invocation Conversion. In this phase, the method invocation conversion via unboxing from Byte to byte would apply, but this phase is never reached.

Related

Java method overloading and varargs

I am trying to understand method overloading, and I have these methods.
public void method(int a){
System.out.println("int a");
}
//implementing interface method
#Override
public void method() {
System.out.println("interface");
}
//varargs
public void method(int ... a){
System.out.println("int ... a");
}
After calling them with these parameters,
int[] a = new int[5];
stack.method();
stack.method(1);
stack.method(5,6);
stack.method(null);
stack.method(a);
I have these results:
interface
int a
int ... a
int ... a
int ... a
As far as I know, the program should not compile, beacuse of ambiguity, but it does anyway. Shouldn't the compiler throw an error?
Eran and Bathsheba have already said why the various ones not using null were chosen.
The rest of the question is: Why does stack.method(null); even compile?
The answer is that it matches the varargs signature, because the varargs method(int...) is effectively the same from the compiler's perspective as method(int[]). Since arrays are referenced by references, null can be used where an int[] is expected.
So:
stack.method();
Exact match for the method() signature in the interface. Not ambiguous with method(int...) because varargs are considered only when others don't match.
stack.method(1);
Matches method(int). Not ambiguous for the same reason as above.
stack.method(5,6);
Matches method(int...) because none of the non-varargs ones matched, but the varargs one did.
stack.method(null);
See earlier explanation.
stack.method(a);
Matches match(int...) for the same reason method(null0 does: Because match(int...) is effectively the same as match(int[]) to the compiler.
Method overloading resolution has three stages. The first and second stages don't consider methods with varargs (also called variable arity methods) as candidates, so only if no matching method without varargs is found, the compiler considers method with varargs as candidates.
Therefore, in the first and second method calls, your void method(int ... a) is ignored, and there is no ambiguity.
15.12.2. Compile-Time Step 2: Determine Method Signature
The second step searches the type determined in the previous step for
member methods. This step uses the name of the method and the argument
expressions to locate methods that are both accessible and applicable,
that is, declarations that can be correctly invoked on the given
arguments.
There may be more than one such method, in which case the most
specific one is chosen. The descriptor (signature plus return type) of
the most specific method is the one used at run time to perform the
method dispatch.
A method is applicable if it is applicable by one of strict invocation
(§15.12.2.2), loose invocation (§15.12.2.3), or variable arity
invocation (§15.12.2.4).
Certain argument expressions that contain implicitly typed lambda
expressions (§15.27.1) or inexact method references (§15.13.1) are
ignored by the applicability tests, because their meaning cannot be
determined until a target type is selected.
Although the method invocation may be a poly expression, only its
argument expressions - not the invocation's target type - influence
the selection of applicable methods.
The process of determining applicability begins by determining the
potentially applicable methods (§15.12.2.1).
The remainder of the process is split into three phases, to ensure
compatibility with versions of the Java programming language prior to
Java SE 5.0. The phases are:
The first phase (§15.12.2.2) performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity
method invocation. If no applicable method is found during this phase
then processing continues to the second phase.
This guarantees that any calls that were valid in the Java programming language before Java SE 5.0 are not considered ambiguous
as the result of the introduction of variable arity methods, implicit
boxing and/or unboxing. However, the declaration of a variable arity
method (§8.4.1) can change the method chosen for a given method method
invocation expression, because a variable arity method is treated as a
fixed arity method in the first phase. For example, declaring
m(Object...) in a class which already declares m(Object) causes
m(Object) to no longer be chosen for some invocation expressions (such
as m(null)), as m(Object[]) is more specific.
The second phase (§15.12.2.3) performs overload resolution while allowing boxing and unboxing, but still precludes the use of variable
arity method invocation. If no applicable method is found during this
phase then processing continues to the third phase.
This ensures that a method is never chosen through variable arity method invocation if it is applicable through fixed arity method
invocation.
The third phase (§15.12.2.4) allows overloading to be combined with variable arity methods, boxing, and unboxing.
A method with a variable argument list is only considered by the compiler once all other possibilities have been exhausted.
These "other possibilities" are considered in the normal way.
Hence in your case there is no ambiguity and so the compiler does not emit an error.
No it is fine there is no ambiguity : passing "(5,6)" is fine because the method expxects many integers , passing "(a)" is also fine because a is an integer array passing"(null)" is also fine beacause null can be cast to any reference type like an integer [] so it can be used where you expect int [];
so all these calls call the third method
public void method(int ... a){
System.out.println("int ... a");
}
the first two method calls are self explanatory they call methods
public void method(){
System.out.println("interface");
}
and
public void method(int a){
System.out.println("int a");
}
respectively

Java Method Overloading with Vararg

I've two versions of addValues, one with vararg parameters.
double addValues(double ... values) {
double result = 0d;
for (double value : values)
result += value;
return result;
}
double addValues(double v1, double v2) {
return v1 + v2;
}
When I call addValues(2, 3) which looks ambiguous to me, why Java selects the addValues(double v1, double v2) version to run the code? How does Java determine which version is 'closer' to the invocation?
Thanks.
This answer gives the relevant section of the Java Language Specification. However it is so complicated that it requires a few examples to explain.
The compiler will always choose a method not needing "variable arity invocation" or auto boxing or auto unboxing if possible. Variable arity invocation is when you invoke a varargs method by passing a parameter list for the last argument (rather than an array).
For example, suppose you have a method with signature
void foo(int... arr)
This is a variable arity invocation...
foo(1, 2, 3);
...but this is not.
foo(new int[] {1, 2, 3});
So in your case, addValues(2, 3) uses the second version as this is not a variable arity invocation.
It is not true to say that the compiler will always favour a method not involving varargs over one that does involve varargs, as this example shows:
public static void bar(int... a) {
System.out.println("Varargs");
}
public static void bar(Object a) {
System.out.println("Object");
}
public static void main(String[] args) {
bar(new int[] {1, 2, 3}); // Prints Varargs
}
In this example, neither choice is a variable arity invocation, but the first version is invoked as it is more specific.
These rules made it possible to change a non-varargs signature
baz(int[] arr)
to a varargs one
baz(int... arr)
without changing the behaviour of any existing program.
The compiler will usually favor a non-varargs overload over a varargs overload. When varargs was added in Java 5, they wanted to add varargs overloads while still remaining backwards compatible, meaning that prior code that was necessarily calling a non-varargs overload would still call that overload and not the varargs overload.
This is explained in the JLS, Section 15.12.2:
The remainder of the process is split into three phases, to ensure compatibility with versions of the Java programming language prior to Java SE 5.0. The phases are:
The first phase (§15.12.2.2) performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the second phase.
This guarantees that any calls that were valid in the Java programming language before Java SE 5.0 are not considered ambiguous as the result of the introduction of variable arity methods, implicit boxing and/or unboxing. However, the declaration of a variable arity method (§8.4.1) can change the method chosen for a given method method invocation expression, because a variable arity method is treated as a fixed arity method in the first phase. For example, declaring m(Object...) in a class which already declares m(Object) causes m(Object) to no longer be chosen for some invocation expressions (such as m(null)), as m(Object[]) is more specific.
The second phase (§15.12.2.3) performs overload resolution while allowing boxing and unboxing, but still precludes the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the third phase.
This ensures that a method is never chosen through variable arity method invocation if it is applicable through fixed arity method invocation.
The third phase (§15.12.2.4) allows overloading to be combined with variable arity methods, boxing, and unboxing.
(bold emphasis mine)

Why does the compiler prefer an int overload to a varargs char overload for a char?

Code
public class TestOverload {
public TestOverload(int i){System.out.println("Int");}
public TestOverload(char... c){System.out.println("char");}
public static void main(String[] args) {
new TestOverload('a');
new TestOverload(65);
}
}
Output
Int
Int
Is it expected behaviour? If so, then why? I am expecting: char, Int
Note: I am using Java 8
Methods with varargs (...) have the lowest priority when the compiler determines which overloaded method to choose. Therefore TestOverload(int i) is chosen over TestOverload(char... c) when you call TestOverload with a single char parameter 'a', since a char can be automatically promoted to an int.
JLS 15.12.2 :
The first phase (§15.12.2.2) performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity
method invocation. If no applicable method is found during this phase
then processing continues to the second phase.
This guarantees that any calls that were valid in the Java programming
language before Java SE 5.0 are not considered ambiguous as the result
of the introduction of variable arity methods, implicit boxing and/or
unboxing. However, the declaration of a variable arity method (§8.4.1)
can change the method chosen for a given method method invocation
expression, because a variable arity method is treated as a fixed
arity method in the first phase. For example, declaring m(Object...)
in a class which already declares m(Object) causes m(Object) to no
longer be chosen for some invocation expressions (such as m(null)), as
m(Object[]) is more specific.
The second phase (§15.12.2.3) performs overload resolution while allowing boxing and unboxing, but still precludes the use of variable arity method invocation. If no applicable method is found during this
phase then processing continues to the third phase. This ensures that a method is never chosen through variable arity
method invocation if it is applicable through fixed arity method
invocation.
The third phase (§15.12.2.4) allows overloading to be combined with variable arity methods, boxing, and unboxing.
EDIT:
It you wish to force the compiler to call the TestOverload(char... c) constructor, you can pass to the constructor call a char[] :
new TestOverload (new char[] {'a'});
Yes, it is expected behaviour. The precedence for method calling goes like this :
Widending
Boxing
Varargs
Below is excerpt from Java docs related to same :-
The process of determining applicability begins by determining the potentially applicable methods (§15.12.2.1).
The remainder of the process is split into three phases, to ensure compatibility with versions of the Java programming language prior to Java SE 5.0. The phases are:
The first phase (§15.12.2.2) performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the second phase.
This guarantees that any calls that were valid in the Java programming language before Java SE 5.0 are not considered ambiguous as the result of the introduction of variable arity methods, implicit boxing and/or unboxing. However, the declaration of a variable arity method (§8.4.1) can change the method chosen for a given method method invocation expression, because a variable arity method is treated as a fixed arity method in the first phase. For example, declaring m(Object...) in a class which already declares m(Object) causes m(Object) to no longer be chosen for some invocation expressions (such as m(null)), as m(Object[]) is more specific.
The second phase (§15.12.2.3) performs overload resolution while allowing boxing and unboxing, but still precludes the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the third phase.
This ensures that a method is never chosen through variable arity method invocation if it is applicable through fixed arity method invocation.
The third phase (§15.12.2.4) allows overloading to be combined with variable arity methods, boxing, and unboxing.
Solid advice from Joshua Bloch (Effective Java, 2nd Ed):
"only choose as arguments for an overloaded method those that have -radically- different types."
An object with a radically different type is one that can not reasonably be cast into another of the argument types. Following this rule can potentially save you hours of debugging a mysterious error that can happen when the compiler chooses at compile time the method overloading that you did not expect.
Your lines of code violate this rule and open the door for bugs:
public TestOverload(int i){System.out.println("Int");}
public TestOverload(char... c){System.out.println("char");}
A char is interconvertible with an int and so the only way you can predict what will happen with the invocations is to go to the Java Language Specification and read the somewhat arcane rules about how overloadings are resolved.
Luckily, this situation shouldn't need JLS research. If you have arguments that are not radically different from each other, probably the best option is to not overload. Give the methods different names so that there is no possibility for error or confusion on the part of anyone who may need to maintain the code.
Time is money.
I took the code from this link and modified some parts of it:
public static void main(String[] args) {
Byte i = 5;
byte k = 5;
aMethod(i, k);
}
//method 1
static void aMethod(byte i, Byte k) {
System.out.println("Inside 1");
}
//method 2
static void aMethod(byte i, int k) {
System.out.println("Inside 2");
}
//method 3
static void aMethod(Byte i, Byte k) {
System.out.println("Inside 3 ");
}
//method 4
static void aMethod(Byte i, Byte ... k) {
System.out.println("Inside 4 ");
}
The compiler gives error (The method is ambiguous for the type Overloading) for methods 1, 2 and 3 but not 4 (why?)
The answer lies in the mechanism which java uses to match method calls to method signatures. The mechanism is done in three phases, in each phase if it finds matching method it stops:
+phase one: use widening to find matching method (no matching methods found)
+phase two: (also) use boxing/unboxing to find matching method (method 1,2 and 3 match)
+phase three: (also) use var args (method 4 matches!)

Method overload ambiguity with Java 8 ternary conditional and unboxed primitives

The following is code compiles in Java 7, but not openjdk-1.8.0.45-31.b13.fc21.
static void f(Object o1, int i) {}
static void f(Object o1, Object o2) {}
static void test(boolean b) {
String s = "string";
double d = 1.0;
// The supremum of types 'String' and 'double' is 'Object'
Object o = b ? s : d;
Double boxedDouble = d;
int i = 1;
f(o, i); // fine
f(b ? s : boxedDouble, i); // fine
f(b ? s : d, i); // ERROR! Ambiguous
}
The compiler claims the last method call ambiguous.
If we change the type of the second parameter of f from int to Integer, then the code compiles on both platforms. Why doesn't the posted code compile in Java 8?
Let's first consider a simplified version that doesn't have a ternary conditional and doesn't compile on Java HotSpot VM (build 1.8.0_25-b17):
public class Test {
void f(Object o1, int i) {}
void f(Object o1, Object o2) {}
void test() {
double d = 1.0;
int i = 1;
f(d, i); // ERROR! Ambiguous
}
}
The compiler error is:
Error:(12, 9) java: reference to f is ambiguous
both method f(java.lang.Object,int) in test.Test and method f(java.lang.Object,java.lang.Object) in test.Test match
According to JLS 15.12.2. Compile-Time Step 2: Determine Method Signature
A method is applicable if it is applicable by one of strict invocation (§15.12.2.2), loose invocation (§15.12.2.3), or variable arity invocation (§15.12.2.4).
Invocation has to do with invocation context which is explained here JLS 5.3. Invocation Contexts
When no boxing or unboxing is involved for a method invocation then strict invocation applies. When boxing or unboxing is involved for a method invocation then loose invocation applies.
Identifying applicable methods is divided into 3 phases.
The first phase (§15.12.2.2) performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the second phase.
The second phase (§15.12.2.3) performs overload resolution while allowing boxing and unboxing, but still precludes the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the third phase.
The third phase (§15.12.2.4) allows overloading to be combined with variable arity methods, boxing, and unboxing.
For our case there are no methods applicable by strict invocation. Both methods are applicable by loose invocation since the double value has to be boxed.
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).
It may look that the 2nd condition matches for this case but in fact it doesn't because int is not a subtype of Object: it's not true that int <: Object. However if we replace int with Integer in the f method signature this condition would match. Note that the 1st parameter in methods matches this condition since Object <: Object is true.
According to $4.10 no subtype/supertype relation is defined between primitive types and Class/Interface types. So int is not a subtype of Object for example. Thus int is not more specific than Object.
Since among the 2 methods there are no more specific methods thus there can be no strictly more specific and can be no most specific method (the JLS gives definitions for those terms in the same paragraph JLS 15.12.2.5 Choosing the Most Specific Method). So both methods are maximally specific.
In this case the JLS gives 2 options:
If all the maximally specific methods have override-equivalent signatures (§8.4.2) ...
This is not our case, thus
Otherwise, the method invocation is ambiguous, and a compile-time error occurs.
The compile-time error for our case looks valid according to the JLS.
What happens if we change method parameter type from int to Integer?
In this case both methods are still applicable by loose invocation. However the method with Integer parameter is more specific than the method with 2 Object parameters since Integer <: Object. The method with Integer parameter is strictly more specific and most specific thus the compiler will choose it and not throw a compile error.
What happens if we change double to Double in this line: double d = 1.0;?
In this case there is exactly 1 method applicable by strict invocation: no boxing or unboxing is required for invocation of this method: f(Object o1, int i). For the other method you need to do boxing of int value so it's applicable by loose invocation. The compiler can choose the method applicable by strict invocation thus no compiler error is thrown.
As Marco13 pointed out in his comment there is a similar case discussed in this post Why is this method overloading ambiguous?
As explained in the answer there were some major changes related to the method invocation mechanisms between Java 7 and Java 8. This explains why the code compiles in Java 7 but not in Java 8.
Now comes the fun part!
Let's add a ternary conditional operator:
public class Test {
void f(Object o1, int i) {
System.out.println("1");
}
void f(Object o1, Object o2) {
System.out.println("2");
}
void test(boolean b) {
String s = "string";
double d = 1.0;
int i = 1;
f(b ? s : d, i); // ERROR! Ambiguous
}
public static void main(String[] args) {
new Test().test(true);
}
}
The compiler complains about ambiguous method invocation.
The JLS 15.12.2 doesn't dictate any special rules related to ternary conditional operators when performing method invocations.
However there are JLS 15.25 Conditional Operator ? : and JLS 15.25.3. Reference Conditional Expressions. The former one categorizes conditional expressions into 3 subcategories: boolean, numeric and reference conditional expression. The second and third operands of our conditional expression have types String and double respectively. According to the JLS our conditional expression is a reference conditional expression.
Then according to JLS 15.25.3. Reference Conditional Expressions our conditional expression is a poly reference conditional expression since it appears in an invocation context. The type of our poly conditional expression thus is Object (the target type in the invocation context). From here we could continue the steps as if the first parameter is Object in which case the compiler should choose the method with int as the second parameter (and not throw the compiler error).
The tricky part is this note from JLS:
its second and third operand expressions similarly appear in a context of the same kind with target type T.
From this we can assume (also the "poly" in the name implies this) that in the context of method invocation the 2 operands should be considered independently. What this means is that when the compiler has to decide whether a boxing operation is required for such argument it should look into each of the operands and see if a boxing may be required. For our specific case String doesn't require boxing and double will require boxing. Thus the compiler decides that for both overloaded methods it should be a loose method invocation. Further steps are the same as in the case when instead of a ternary conditional expression we use a double value.
From the explanation above it seems that the JLS itself is vague and ambiguous in the part related to conditional expressions when applied to overloaded methods so we had to make some assumptions.
What's interesting is that my IDE (IntelliJ IDEA) doesn't detect the last case (with the ternary conditional expression) as a compiler error. All other cases it detects according to the java compiler from JDK. This means that either JDK java compiler or the internal IDE parser has a bug.
In short:
The compiler doesn't know which method to choose since the ordering between primitive and reference types is not defined in JLS in regards to choosing most specific method.
When you use Integer instead of int the compiler picks the method with Integer because Integer is a subtype of Object.
When you use Double instead of double the compiler picks the method that doesn't involve boxing or unboxing.
Prior to Java 8 the rules were different so this code could compile.

Overloading var-args

Who can explain why first method preferable than second?
I know this rules for overloading (except first of all compiler find appropriate args)
widening
autoboxing
var-args
Code:
public class Proba{
public static void show(Object ... args){
System.out.println("Object ...");
}
public static void show(Integer[] ... args){
System.out.println("Integer ...");
}
public static void main(String[] args) {
Integer[] array = {3,2,5,1};
show(array);
}
}
Console : Object ...
The rules of method resolution in Java require that a match be attempted without auto-(un)boxing and variable arity before attempting a match with those features. This ensures source compatibility with language versions that predate those features.
The rules for overload resolution are described in the JLS (§15.12.2):
The process of determining applicability begins by determining the potentially
applicable methods (§15.12.2.1).
The remainder of the process is split into three phases, to ensure compatibility with
versions of the Java programming language prior to Java SE 5.0. The phases are:
The first phase (§15.12.2.2) performs overload resolution without permitting
boxing or unboxing conversion, or the use of variable arity method invocation.
If no applicable method is found during this phase then processing continues
to the second phase.
This guarantees that any calls that were valid in the Java programming language
before Java SE 5.0 are not considered ambiguous as the result of the introduction of
variable arity methods, implicit boxing and/or unboxing. However, the declaration of
a variable arity method (§8.4.1) can change the method chosen for a given method
method invocation expression, because a variable arity method is treated as a fixed
arity method in the first phase. For example, declaring m(Object...) in a class which
already declares m(Object) causes m(Object) to no longer be chosen for some
invocation expressions (such as m(null)), as m(Object[]) is more specific.
The second phase (§15.12.2.3) performs overload resolution while allowing
boxing and unboxing, but still precludes the use of variable arity method
invocation. If no applicable method is found during this phase then processing
continues to the third phase.
This ensures that a method is never chosen through variable arity method invocation
if it is applicable through fixed arity method invocation.
The third phase (§15.12.2.4) allows overloading to be combined with variable
arity methods, boxing, and unboxing.
Deciding whether a method is applicable will, in the case of generic methods
(§8.4.4), require that type arguments be determined. Type arguments may be
passed explicitly or implicitly. If they are passed implicitly, they must be inferred
(§15.12.2.7) from the types of the argument expressions.
If several applicable methods have been identified during one of the three phases
of applicability testing, then the most specific one is chosen, as specified in section
§15.12.2.5.
In your example, there are two candidates during Step 1: the method with an Object[] parameter, and the method with an Integer[][] parameter. The argument type at your call site is Integer[]. Since Object[] is assignable from Integer[], but Integer[][] is not, a single applicable method has been found, and overload resolution halts there. Steps 2 and 3 are never reached in this case.
Mike is correct; there are 3 phases,
15.12.2.2. Phase 1: Identify Matching Arity Methods Applicable by Subtyping
15.12.2.3. Phase 2: Identify Matching Arity Methods Applicable by Method Invocation Conversion
15.12.2.4. Phase 3: Identify Applicable Variable Arity Methods
show(Object[]) is chosen in the first phase, but show(Integer[]...) can only be chosen in the 3rd phase.
If the first method signature is changed to show(Object[] ... args), you'll see the expected result.
If the second method signature is changed to show(Integer ... args), you'll also see the expected result. The method also fits in phase 1, and it is more specific than show(Object...)
If we have
public static void show(Object ... args){
System.out.println("Object ...");
}
static class IntArray{}
public static void show(IntArray ... args){
System.out.println("IntArray ...");
}
show(new IntArray());
it prints the expected IntArray .... Here IntArray is not a subtype of Object[].
This is all too confusing. Programmers usually don't know about these phases; they think about all applicable methods and the most specific one among them. It might have been better if the spec does that too.

Categories

Resources