I needed to dig into the specifics of method invocation in Java, and while reading the section Choosing the Most Specific Method in The Java Language Specification (Java SE 12 Edition), I found that (1) during invocation multiple methods can be maximally specific and that (2) having multiple maximally specific methods doesn't always result in a compile-time error.
I was able to think of an example where two methods are both maximally specific:
interface A {}
interface B {}
class C implements A, B {
<T extends A> void foo(T t) {};
<T extends B> void foo(T t) {};
}
class Main {
public static void main(String[] args) {
new C().<C>foo(null);
}
}
This example results in a compile-time error: error: reference to foo is ambiguous
This makes sense to me, but what doesn't make sense to me is when there are multiple maximally specific methods and it doesn't result in a compile-time error.
The section Choosing the Most Specific Method in The Java Language Specification (Java SE 12 Edition) mentions two scenarios where the compiler is able to select a method when there are multiple maximally specific methods:
If all the maximally specific methods have override-equivalent signatures (§8.4.2), and exactly one of the maximally specific methods is concrete (that is, neither abstract nor default), then it is the most specific method.
Otherwise, if all the maximally specific methods have override-equivalent signatures, and all the maximally specific methods are abstract or default, and the declarations of these methods have the same erased parameter types, and at least one maximally specific method is preferred according to the rules below, then the most specific method is chosen arbitrarily among the subset of the maximally specific methods that are preferred. The most specific method is then considered to be abstract.
First, how is it possible to invoke a method that is abstract
? Why would an abstract
method ever be considered for method invocation?
Second, can someone provide an example for each of these two scenarios that don't result in compile-time errors?