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?
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
Then the compiler has the choice of two "applicable methods". You're actually calling the more specific method
Which will give you a
NullPointerException
. In order to call the other method, writeIn this case, you remain with only one "applicable method", so you don't have the problem of a different, overloaded method being "more specific".
"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.
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 givesjava.lang.Object
and therefore in case when null is not explicitly cast compiler choosesvalueOf(char[])
overvalueOf(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. :)
If the cast where not performed, then the most specific version would be chosen.
null
could be a null-reference of typeString
or of typeObject
. So if those two methods are available, then theString
method will be called.If you have methods with
Object
,Integer
andString
then calling that withnull
(and no cast) would give a compilation error becauseInteger
andString
are both valid and equally specific (i.e. none is a specialization of the other). In that case you would have to castnull
to specify which method to call.