In two days i have an exam in java, and i can not figure out the answer to this question:
class ClassA {
public String foo(Integer x , int y) {
return "Integer, int";
}
public String foo(int x, Double y) {
return "int, Double";
}
public String foo(Number x, Number y) {
return "Number, Number";
}
public String foo(Object x, Object y) {
return "Object, Object";
}
public static void main(String... args) {
ClassA a = new ClassA();
System.out.print(a.foo(5, 1.2f) + " ");
System.out.println(a.foo(null, null));
}
}
What’s the output?
The Answer is:
Number, Number Number, Number
I know that java always chooses the most specified Method, that is why a.foo(null,null); will envoke the Number,Number Method and not the Object,Object Method.
But why does a.foo(5,1.2f); also envoke the Number,Number Method and not the int,Double Method??
But one more thing which might be helpful:
If i remove the f after 1.2, so that the call is:
a.foo(5,1.2);
I get a compiler error, that it can not choose between the Number,Number and int,Double Method…
Would be really helpful, if you guys could explain that to me 🙂
1.2fis not wrapped by aDouble, it’s wrapped by aFloat. SinceFloatis not a subclass ofDouble(they are distinct subclasses ofNumber), the most specific method signature that can be used isfoo(Number,Number).Once you remove the
f, 1.2 will be treated adouble(the primitive, not the wrapper class) by default, which can be autoboxed to aDouble. However the 5 can also be autoboxed to anInteger, thus causing the ambiguity.