I found this Java code from this site. I don't understand how it compiles without ambiguous error.
package swain.test;
public class Test {
public static void JavaTest(Object obj) {
System.out.println("Object");
}
public static void JavaTest(String arg) {
System.out.println("String");
}
public static void main(String[] args) {
JavaTest(null);
}
}
Output:
String
When we pass a null value to the method1 the compiler gets confused which method it has to select, as both are accepting the null. This compile time error wouldn't happen unless we intentionally pass null value.
So when you pass null as a parameter than compiler gets confused that which object method to call i.e. With parameter Object or parameter Integer since they both are object and their reference can be null. But the primitives in java does not extends Object.
No, you cannot overload a method based on different return type but same argument type and number in java. same name. different parameters (different type or, different number or both).
So can you override an overloaded function? Yes, since the overloaded method is a completely different method in the eyes of the compiler.
null
can be passed to both JavaTest(String arg)
and JavaTest(Object obj)
, so the compiler chooses the method with the more specific argument types. Since String
is more specific than Object
(String
being a sub-class of Object
), JavaTest(String arg)
is chosen.
If instead of JavaTest(Object obj)
you had JavaTest(Integer obj)
, the compilation would have failed, since Integer
is not more specific than String
and String is not more specific than
Integer`, so the compiler wouldn't be able to make a choice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With