• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overloading in Combination with Var-args

 
kiruthigha rajan
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hai can anyone explain me how does the code work??
im unable to understand!!!
thanks in advance

class Vararg {
static void wide_vararg(long... x)
{ System.out.println("long..."); }
static void box_vararg(Integer... x)
{ System.out.println("Integer..."); }
public static void main(String [] args) {
int i = 5;
wide_vararg(i,i); // needs to widen and use var-args
box_vararg(i,i); // needs to box and use var-args
}
}
 
Dan Drillich
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Kiruthigha,

Can you please be more specific about your question?

Regards,
Dan
 
ujjawal rohra
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When calling a method if there is no method matching the exact signature of the called method then the arguments are widened or boxed as required.

The method wide_vararg(long... x) takes a var-arg of type long, that means it can take one or more than one long arguments.
Now when this method is invoked using wide_vararg(i,i) having two ints, then the two ints are matched due to the var-args in the declaration of the method and also the ints are widened and promoted to longs. In this way this method matches the call and is called.

Similarly, when calling box_vararg(i,i), the arguments(two ints) are matched due to var-args declaration and then they are boxed due to an Integer in the declaration.

Hope this helps..
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic