Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
108 views
in Technique[技术] by (71.8m points)

java - Why cast null to Object?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...