| Author |
var-args and overloading
|
Amitav Chowdhury
Greenhorn
Joined: Nov 13, 2009
Posts: 10
|
|
Can some one tell me why the following code does not compile ?
|
 |
Harpreet Singh janda
Ranch Hand
Joined: Jan 14, 2010
Posts: 317
|
|
Because int is applicable for both - int and double.
If you try by passing a double value, it will work fine
|
 |
Rajeev Rnair
Ranch Hand
Joined: Mar 22, 2010
Posts: 308
|
|
Because int can be widened to a double, so it gives ambigous method.
If you change the double to a short, it will compile
Or else instead of passing int you can pass a float or double.
|
 |
Amitav Chowdhury
Greenhorn
Joined: Nov 13, 2009
Posts: 10
|
|
Following the same logic below code should not compile:
But it compiles fine giving the ouput "Integer". Any idea why the behaviors are different for var-args and auto boxing?
|
 |
W. Joe Smith
Ranch Hand
Joined: Feb 10, 2009
Posts: 710
|
|
Amitav Chowdhury wrote:Following the same logic below code should not compile:
public class Overloading {
static void overload(Integer x){
System.out.println("Integer");
}
static void overload(Double d){
System.out.println("Double");
}
public static void main( String args[]) {
int i=1;
overload(1);
}
}
But it compiles fine giving the ouput "Integer". Any idea why the behaviors are different for var-args and auto boxing?
I suggest looking at this link here. It explains some basic rules of widening, boxing and var-args.
|
 |
rushikesh sawant
Ranch Hand
Joined: Dec 22, 2009
Posts: 65
|
|
|
Wrappers are peers to each other. They cannot be converted from one type to other.
|
SCJP 5.0 100%
|
 |
Rajeev Rnair
Ranch Hand
Joined: Mar 22, 2010
Posts: 308
|
|
rushikesh sawant wrote:Wrappers are peers to each other. They cannot be converted from one type to other.
very correct!
All wrapper classes inherit from abstract class "Number" except for Boolean and Character.
A Double is a Number
An Integer is a Number
But Double is NOT an Integer
hope this helps!
|
 |
 |
|
|
subject: var-args and overloading
|
|
|