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.
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