wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Overloaded method question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Overloaded method question" Watch "Overloaded method question" New topic
Author

Overloaded method question

Cliff DeRose
Greenhorn

Joined: Jan 08, 2004
Posts: 13
What is the rule for determining which overloaded version of a method to call when the parameter being passed into a particular method has to be implicitly cast? See the following code sample:

If you run this program, the output will be:
Int Method
25
If you think about it, a byte can be implicitly cast to any of the methods in V. I would think this should be ambiguous and cause a compiler error, however, it doesn't.
In cases like this, will the method with an argument which can represent the least range of values always be used? To clarify further, if you have the following:
Example 1:
int abs(int a)
long abs(long a)
The version which takes an int will always be used if the parameter coming in is of a type which has to be implicitly cast.
Example 2:
long abs(long a)
float abs(float a)
The version which takes a long will always be used if the parameter coming in is of a type which has to be implicitly cast.
Thanks,
Cliff
[ January 11, 2004: Message edited by: Cliff DeRose ]
Kristof Camelbeke
Ranch Hand

Joined: Nov 28, 2001
Posts: 97
The compiler will take the most specific method... The argument that was passed was a byte so the most specific method will be the one who takes an int...
Hope I'm clear...
Kristof
Cliff DeRose
Greenhorn

Joined: Jan 08, 2004
Posts: 13
How does the compiler determine what the most "specific" method is?
I found this in the JLS. The following line in particular I think fits my previous example...
The informal intuition is that one method declaration is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.
In this case invoking p.abs(b), V.abs(int a) is more specific than V.abs(float a) or V.abs(double a) because invoking V.abs(int a) could easily be passed on to V.abs(float a) without a problem.
Is this a correct interpretation of the rule?
Cliff
[ January 11, 2004: Message edited by: Cliff DeRose ]
[ January 11, 2004: Message edited by: Cliff DeRose ]
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Overloaded method question