I found a spot in some code I'm working on where null
is cast to Object
as it is passed to a method.
Why would this be done?
I am aware of this question which deals with overloaded methods, and using the cast to determine which version of the method to call.
But if the cast were not performed, wouldn't an overloaded method with a parameter typed as Object
be chosen over any other matching version of the method if the method is called with a null argument? So what else does the cast accomplish?
If the cast where not performed, then the most specific version would be chosen.
null
could be a null-reference of type String
or of type Object
. So if those two methods are available, then the String
method will be called.
If you have methods with Object
, Integer
and String
then calling that with null
(and no cast) would give a compilation error because Integer
and String
are both valid and equally specific (i.e. none is a specialization of the other). In that case you would have to cast null
to specify which method to call.
The "Object
method" is always the "least specific" method among all "applicable methods". That's why it wouldn't be chosen by the compiler.
If you run
String.valueOf(null);
Then the compiler has the choice of two "applicable methods". You're actually calling the more specific method
String.valueOf((char[]) null);
Which will give you a NullPointerException
. In order to call the other method, write
String.valueOf((Object) null);
In this case, you remain with only one "applicable method", so you don't have the problem of a different, overloaded method being "more specific".
Though previous answers already explains what happens if you cast null to Object vs. if you don't cast null to Object, but I would still like to add few missing points.
So in Java, 'arrays' are objects which means they can be assigned to Object type i.e. if you do new char[0].getClass().getSuperclass()
it gives java.lang.Object
and therefore in case when null is not explicitly cast compiler chooses valueOf(char[])
over valueOf(Object)
as the most applicable method.
However, here comes the missing part, had there been another overloaded method that was accepting a interface type param (remember interface don't extend Object class so they too cause ambiguity in most specific method selection) e.g. valueOf(CharSequence) then this would have lead to compile time error (i.e. reference to valueOf is ambiguous) because then compiler could't pick the most applicable method.
So the bottom line is avoid passing raw null as arguments to methods rather always cast them to param type of the method being called. :)
"But if the cast were not performed, wouldn't an overloaded method with a parameter typed as Object be chosen over any other matching version of the method if the method is called with a null argument? "
No, because 'null' has no type - you'd get a compilation error.