• Post Reply Bookmark Topic Watch Topic
  • New Topic

java overloading help..  RSS feed

 
Mohd Shariq
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


output : second 5;

i am new to java want to know d ans of this question
when i run this code i got the result second 5;
i want to know why second 5,why not first 5;
because i create only one object of Testb class so how it check which method to be called ,when both the method are of same name
please reply me i am confused...............
 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are a set of rules that determine which overloaded method gets called when there are more than one that could be called, like in this case. They can get a little tricky, but the overriding principle is "the method that most closely matches the argument type is called".

So, in this example, 5 is an int. It could be autoboxed to an Integer to call the first of your methods, but the second method is a closer match as it doesn't involve any conversion at all.

If you want to know more about it, the order goes something like:

- exact matches
- widening conversions (in order of how far the type would have to be widened)
- autoboxed/unboxed matches
- autoboxed/unboxed followed by a widening conversion (but never a widening followed by a boxing!)
- var-arg matches

So the call a(5) would match any of the following, in order of preference:
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
. . . and welcome to the Ranch
 
Mohd Shariq
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you for replying.
it's very helpful to me.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!