This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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 ]
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
Joined: Jan 08, 2004
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 ]