Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Passing primitive values to methods and method overloading

 
Sathya Srinivasan
Ranch Hand
Posts: 379
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am preparing for my SCJP exam and when I was looking through JavaRanch's previously posted questions, the following problem occured to me.
Consider the following code.

The above program compiles and runs fine. But due to the widening conversions, both the methods are valid. In such a case, I would have expected the first occuring method in the program to be called.
However, the compiler seems to be kind of smart and calls the method that has the closest widening conversion. I verified this with another function with signature

and it picked that method.
Can anyone explain the reasoning behind this?
 
Sathya Srinivasan
Ranch Hand
Posts: 379
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As an addenda,
The output of the first piece was "DFF" and that of the second piece was "DLI".
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sathya,
the compiler chooses the most specific method regardless of their ordered appearance within the class.
Read JLS 15.12.2.2 Choose the Most Specific Method and following for some example.
Moreover, we'd like you to read the Javaranch Naming Policy and register again.
Thank you for your cooperation.
 
Sathya Srinivasan
Ranch Hand
Posts: 379
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Thanks for the information.. Thanks for informing me about the naming policy too. I have changed it accordingly.
 
Mc Fly
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So what do we reckon is the reasoning?
The spec seems to deal with reference types rather than primitives and conversions.
I would have thought that rather than allow a possible loss of information in the least significant digits of the long in the conversion to float the compiler would have chosen the first method
ie. output : DDD
Cheers -McFly
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic