Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why cast null to Object?

Tags:

java

null

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?

like image 893
Tom Tresansky Avatar asked Apr 27 '11 14:04

Tom Tresansky


1 Answers

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.

like image 112
Joachim Sauer Avatar answered Sep 28 '22 11:09

Joachim Sauer