Why does this code print 2.0 and not 1.0?
abstract class B<T extends Number> {
abstract Number f(T j);
}
class A<T extends Number> extends B<T> {
public Number f(Float j) {
return 1f;
}
public Number f(T j) {
return j;
}
}
public class J {
public static void main(String[] args) {
B<Float> a = new A<>();
Number r = a.f(2f);
System.out.println(r);
}
}
So the heart of the problem here is that you have declared the variable
ato be of typeB. Since theBclass has only one method, that’s the one that wins. However, in yourmain, if you change the type ofato be of typeA, you’ll notice that it will not compile because it is ambiguous. However, if you did change the method in the classAto accept a primitive instead, and in themain()method defined the variableato be of typeA, it would result in1.0. I.e., the following will result in printing1.0: