Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

A simple java doubt  RSS feed

 
vijay kumarg
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please see this code:



If both method parameters can take null as a value for them, why the version f(String) is only getting executed?
[ January 22, 2007: Message edited by: vijayk gopu ]
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The rule is that the compiler picks the most specific applicable overload. Because String is a subclass of Object, the String method is more specific than the Object one, and so the String one is chosen -- there is no ambiguity.
 
vijay kumarg
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ernest!
 
Kiran Gavate
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have another question that comes to mind after reading this.

Does the above mean that the object version will never be executed when it is overloaded with other versions accepting other of object?

Suppose we have other overloaded methods in the above code accepting different objects as parameters, will the version void f(Object o) ever be executed? If yes, in which case?

Kiran
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note the word "applicable" in Ernests reply. No matter how many overloaded methods there are, it may be that none fits the object that is passed to the method at runtime. In that case, the "Object" method would be the one being called, because it is the only one that fits.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!