Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

var-args and overloading

 
Amitav Chowdhury
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can some one tell me why the following code does not compile ?

 
Harpreet Singh janda
Ranch Hand
Posts: 317
Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 310
1
Java Linux Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wrappers are peers to each other. They cannot be converted from one type to other.
 
Rajeev Rnair
Ranch Hand
Posts: 310
1
Java Linux Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic