• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overloading and var args

 
Gilles Marceau
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

the following code doesn't compile, and i wonder why :

class TestVarArg {
public void doStuff(int[] args) {

}
public void doStuff(int... args) {

}
}

I tough that overloading is allowed if the method argument list is different, and that's the case in this example.
But it doesn't compile, so it seems that, behind the scene, the var
arg is an array (which makes sense, as "args" in doStuff(int... args)
method body is handled as an array).

Does anyone have a clue about this ?
 
satishkumar janakiraman
Ranch Hand
Posts: 334
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

What compilation errors did you get ? Post your error. I do not see any mistake in your code. It is perfectly correct if the methods are overloaded. For eg doStuff(int[] args) and doStuff(int args)

bye for now
sat
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Giles,

Welcome to JavaRanch!

The code doesn't compile because the two method signatures are the same -- they're two different ways of making the identical declaration. A final argument using the varargs notation is actually compiled into an array argument. One interesting consequence of this is that you can call a method declared using array argument syntax by using the varargs syntax -- for example

List<String> list = Arrays.asList("one", "two", "three");

works just fine.
 
Gilles Marceau
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for your answer, i am now a bit more educated about the var args feature.
 
Remko Strating
Ranch Hand
Posts: 893
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think this code will not compile, because there are duplicate methods defined

With the VarArgs there could be used a Array of integers of which the size is not known. This could be 0 to many.

The other method defines a Array of integers.

So the compiler doesn't know which method to choose.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic