Java 8 type inference bug? [duplicate] - java

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.

Related

Method reference is ambiguous for Thread.sleep

I've come across a weird problem where a method reference to Thread::sleep is ambiguous but a method with the same signature is not.
package test;
public class Test
{
public static void main(String[] args)
{
foo(Test::sleep, 1000L); //fine
foo((FooVoid<Long>)Thread::sleep, 1000L); //fine
foo(Thread::sleep, 1000L); //error
}
public static void sleep(long millis) throws InterruptedException
{
Thread.sleep(millis);
}
public static <P, R> void foo(Foo<P, R> function, P param) {}
public static <P> void foo(FooVoid<P> function, P param) {}
#FunctionalInterface
public interface Foo<P, R> {
R call(P param1) throws Exception;
}
#FunctionalInterface
public interface FooVoid<P> {
void call(P param1) throws Exception;
}
}
I get those 2 errors:
Error:(9, 17) java: reference to foo is ambiguous
both method <P,R>foo(test.Test.Foo<P,R>,P) in test.Test and method <P>foo(test.Test.FooVoid<P>,P) in test.Test match
Error:(9, 20) java: incompatible types: cannot infer type-variable(s) P,R
(argument mismatch; bad return type in method reference
void cannot be converted to R)
The only difference I see is that Thread::sleep is native. Does it change anything? I don't think the overload Thread::sleep(long, int) comes into play here. Why does it happen?
EDIT: Using javac version 1.8.0_111
You can recreate the problem in your own class by adding a method sleep with two arguments to class Test like below:
public static void sleep(long millis) {
}
public static void sleep(long millis, int nanos) {
}
So the problem is really caused by the fact that the method sleep is overloaded.
The JLS indicates that the initial method selection code only looks at the number of type arguments to the functional interface - only in the second phase does it look at the signature of the method inside the functional interface.
JLS 15.13:
It is not possible to specify a particular signature to be matched,
for example, Arrays::sort(int[]). Instead, the functional interface
provides argument types that are used as input to the overload
resolution algorithm (§15.12.2).
(the second-to-last paragraph of this section)
So in the case of Thread::sleep, void sleep(long) potentially matches functional interface FooVoid<P>, while overload void sleep(long, int) potentially matches functional interface Foo<P, R>. That's why you get the "reference to foo is ambiguous" error.
When it tries to go further and see how to match Foo<P, R> with functional method R call(P param1) to the method void sleep(long, int), it finds out that this is not actually possible, and you get another compile error:
test/Test.java:7: error: incompatible types: cannot infer type-variable(s) P,R
foo(Thread::sleep, 1000L); // error
^
(argument mismatch; bad return type in method reference
void cannot be converted to R)
The problem is that both, Thread.sleep and foo, are overloaded. So there is a circular dependency.
In order to find out which sleep method to use, we need to know the target type, i.e. which foo method to invoke
In order to find out which foo method to invoke, we need to know the functional signature of the argument, i.e. which sleep method we have selected
While it’s clear to a human reader that for this scenario only one of the 2×2 combinations is valid, the compiler must follow formal rules that work for arbitrary combinations, therefore, the language designers had to make a cut.
For the sake of usefulness of method references, there is a special treatment for unambiguous references, like your Test::sleep:
JLS §15.13.1
For some method reference expressions, there is only one possible compile-time declaration with only one possible invocation type (§15.12.2.6), regardless of the targeted function type. Such method reference expressions are said to be exact. A method reference expression that is not exact is said to be inexact.
Note that this distinction is similar to the distinction between implicitly typed lambda expressions (arg -> expression) and explicitly typed lambda expressions ((Type arg) -> expression).
When you look at JLS, §15.12.2.5., Choosing the Most Specific Method, you’ll see that the signature of a method reference is only used for exact method references, as when choosing the right foo, the decision for the right sleep method has not made yet.
If e is an exact method reference expression (§15.13.1), then i) for all i (1 ≤ i ≤ k), Ui is the same as Vi, and ii) one of the following is true:
R₂ is void.
R₁ <: R₂.
R₁ is a primitive type, R₂ is a reference type, and the compile-time declaration for the method reference has a return type which is a primitive type.
R₁ is a reference type, R₂ is a primitive type, and the compile-time declaration for the method reference has a return type which is a reference type.
The above rule has been stated in §15.12.2.5. for non-generic methods, redirecting to §18.5.4 for generic methods (which applies here as your foo methods are generic), containing exactly the same rule with a slightly different wording.
Since the method reference’s signature is not considered when choosing the most specific method, there is no most specific method and the invocation of foo is ambiguous. The second compiler error is the result of the strategy to continue processing the source code and potentially reporting more errors, instead of stopping the compilation right at the first error. One of the two invocations of foo caused an “incompatible types” error, if that invocation was happening, but actually that has been ruled out due to the “ambiguous invocation” error.
Personally I see this as some sort of recursion, somehow like this: we need to resolve the method in order to find the target type, but we need to know the target type in order to resolve the method. This has something to do with a special void compatibility rule, but I admit I do not entirely get it.
Things are even funner when you have something like this:
public static void cool(Predicate<String> predicate) {
}
public static void cool(Function<String, Integer> function) {
}
And try to call it via:
cool(i -> "Test"); // this will fail compilation
And btw if you make your lambda explicit, this will work:
foo((Long t) -> Thread.sleep(t), 1000L);

Ambiguous varargs methods with Object and primitive type

Consider the following two sets of methods. The first one is accepted, the second one is rejected as ambiguous. The only difference is between using int and Integer.
Is there a particular need to reject the second one? That would imply that accepting it after boxing (which would lead to the first set) has a problem. What do I miss here?
From my point of view, the Java compiler is too restrictve here.
Set 1:
public void test(Object... values) {}
public void test(Integer x, Object... values) {} // difference here
public void b() {
test(1, "y"); // accepted
}
Set 2:
public void test(Object... values) {}
public void test(int x, Object... values) {} // difference here
public void b() {
test(1, "y"); // marked as ambiguous
}
Set 2 produces the compiler error:
error: reference to test is ambiguous
test(1, "y"); // marked as ambiguous
^
both method test(Object...) in T and method test(int,Object...) in T match
Java 1.8, Eclipse Oxygen
What the compiler doing is implementing the rules set out in JLS 15.12.2.5 for choosing the most specific method in the cases where multiple methods are applicable for the invocation. In the examples in your question, the difference is covered by this line in the spec:
A type S is more specific than a type T for any expression if S <: T (§4.10).
where S <: T means that S is a subtype of T.
In example #1:
There are two applicable methods
The type Integer is a subtype of Object, so it is more specific.
Therefore the second method is more specific than the first.
Therefore the second method is chosen.
In example #2:
There are two applicable methods
The type int is not a subtype of Object or vice versa, so neither type is more specific than the other.
Therefore the neither method is more specific than the other.
Therefore the invocation is ambiguous.
The difference is that in the first case, the 1 argument needs to be boxed into Integer, and then the most fitting method chosen; that being the (Integer, Object...) version.
In the second case, there are two options - boxing or not. This is what makes it ambiguous.
I agree that this is counter-intuitive.
To close this issue, let me summarize actual answers to my question as I understand them: the behaviour is correct according to the specification. The specification could be relaxed such that primitive types are covered as their non-primitive counterparts. One reason that's not done yet is the complexity of specifying and implementing a fast and correct parser.

Java method specificity [duplicate]

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.

Why can't javac infer generic type arguments for functions used as arguments?

In the following sample, why is the compiler able to infer the generic arguments for the first call to Foo.create() in Foo.test(), but not able to do so in the second? I'm using Java 6.
public class Nonsense {
public static class Bar {
private static void func(Foo<String> arg) { }
}
public static class Foo<T> {
public static <T> Foo<T> create() {
return new Foo<T>();
}
private static void test() {
Foo<String> foo2 = Foo.create(); // compiles
Bar.func(Foo.create()); // won't compile
Bar.func(Foo.<String>create()); // fixes the prev line
}
}
}
(The compile error is The method func(Nonsense.Foo) in the type Nonsense.Bar is not applicable for the arguments (Nonsense.Foo)).
Note: I understand the compiler error can be fixed by the third line in test() - I'm curious as to whether there is a specific limitation that prevents the compiler from being able to infer the type. It appears to me that there is enough context for it here.
As of Java 7, method overload resolution has to proceed before any target type information from the method you are calling can be taken into account to try to infer the type variable T in the declaration of func. It seems foolish, since we can all see that in this case there is one and only one method named func, however, it is mandated by the JLS and is the behavior of javac from Java 7.
Compilation proceeds as follows: First, the compiler sees that it is compiling a call to a static method of class Bar named func. To perform overload resolution, it must find out what parameters the method is being called with. Despite this being a trivial case, it must still do so, and until it has done so it does not have any information about the formal parameters of the method available to help it. The actual parameters consist of one argument, a call to Foo.create() which is declared as returning Foo<T>. Again, with no criteria from the target method, it can only deduce that the return type is the erasure of Foo<T> which is Foo<Object>, and it does so.
Method overload resolution then fails, since none of the overloads of func is compatible with an actual parameter of Foo<Object>, and an error is emitted to that effect.
This is of course highly unfortunate since we can all see that if the information could simply flow in the other direction, from the target of the method call back towards the call site, the type could readily be inferred and there would be no error. And in fact the compiler in Java 8 can do just that, and does. As another answer stated, this richer type inferencing is very useful to the lambdas that are being added in Java 8, and to the extensions to the Java APIs that are being made to take advantage of lambdas.
You can download a pre-release build of Java 8 with JSR 335 lambdas from the preceding link. It compiles the code in the question without any warnings or errors.
Inferring types from context is too complicated. The main obstacle is probably method overloading. For example, f(g(x)), to determine which f() to apply, we need to know the type of g(x); yet the type of g(x) may need to be inferred from f()'s parameter types. In some languages method overloading is simply prohibited so that type inference can be easier.
In Java 8 your example compiles. The Java team is more motivated to broaden type inference due to lambda expression use cases. It's not an easy task.
The java language specification for java 7 contains 40 pages just to spec method invocation expression (section 15.12)

overloading with both widening and boxing

public void add(long... x){}
public void add(Integer... x){}
add(2);
this produces error...why overlaoding is not performed with both widening and boxing?
but overloading without vararg works fine
public void add(long x){}
public void add(Integer x){}
add(2);
here add(long x) will be executed that is widening beats boxing...why not same concept with
var arguments
Java compiler performs three attempts to choose an appropriate method overload (JLS §15.12.2.1):
Phase 1: Identify Matching Arity Methods Applicable by Subtyping
(possible boxing conversions and methods with varargs are ignored)
Phase 2: Identify Matching Arity Methods Applicable by Method
Invocation Conversion
(takes boxing conversion in account, but ignores methods with varargs)
Phase 3: Identify Applicable Variable Arity Methods
(examines all possibilities)
So, with your examples it works as follows:
Without varargs: add(long x) is identified as the only applicable method on the 1st phase (this method is applicable by subtyping since int is a subtype of long, §JLS 4.10.1), so that following phases are not executed.
With varargs: overload resoltion algorithm goes to phase 3, where both methods are identified as applicable, and compiler can't choose the most specific method of them (choosing the most specific method is yet another complex algorithm), therefore it reports ambiguity.
See also:
The Java Language Specification, Seventh Edition
because it is ambiguous.
2 can be Integer as well as long and it can be resolve to both. you made compiler confused whom to invoke :)
5.12.2.2 Choose the Most Specific Method
If 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.
The precise definition is as follows.
Let m be a name and suppose that there
are two declarations of methods named
m, each having n parameters. Suppose
that one declaration appears within a
class or interface T and that the
types of the parameters are T1, . . .
, Tn; suppose moreover that the other
declaration appears within a class or
interface U and that the types of the
parameters are U1, . . . , Un. Then
the method m declared in T is more
specific than the method m declared in
U if and only if both of the following
are true:
T can be converted to U by method
invocation conversion. Tj can be
converted to Uj by method invocation
conversion, for all j from 1 to n. A
method is said to be maximally
specific for a method invocation if it
is applicable and accessible and there
is no other applicable and accessible
method that is more specific. If there
is exactly one maximally specific
method, then it is in fact the most
specific method; it is necessarily
more specific than any other method
that is applicable and accessible. It
is then subjected to some further
compile-time checks as described in
§15.12.3.
It is possible that no method is the
most specific, because there are two
or more maximally specific methods. In
this case:
If all the maximally specific methods
have the same signature, then: If one
of the maximally specific methods is
not declared abstract, it is the most
specific method. Otherwise, all the
maximally specific methods are
necessarily declared abstract. The
most specific method is chosen
arbitrarily among the maximally
specific methods. However, the most
specific method is considered to throw
a checked exception if and only if
that exception is declared in the
throws clauses of each of the
maximally specific methods. Otherwise,
we say that the method invocation is
ambiguous, and a compile-time error
occurs.
15.12.2.3 Example: Overloading Ambiguity
Consider the example:
class Point { int x, y; }
class ColoredPoint extends Point { int color; }
class Test {
static void test(ColoredPoint p, Point q) {
System.out.println("(ColoredPoint, Point)");
}
static void test(Point p, ColoredPoint q) {
System.out.println("(Point, ColoredPoint)");
}
public static void main(String[] args) {
ColoredPoint cp = new ColoredPoint();
test(cp, cp); // compile-time error
}
}
This example produces an error at compile time. The problem is that there are two declarations of test that are applicable and accessible, and neither is more specific than the other. Therefore, the method invocation is ambiguous.
If a third definition of test were added:
static void test(ColoredPoint p, ColoredPoint q) {
System.out.println("(ColoredPoint, ColoredPoint)");
}
then it would be more specific than the other two, and the method invocation would no longer be ambiguous.
Read More

Categories