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 / no-args constructor

 
Christian Kindler
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following code is from Bates, Bert and Kathy Sierra. "SCJP SunĀ® Certified Programmer for JavaTM 6 Study Guide" (Master Exam):



Because there is no no-arg (default) constructor I would assume that the compiler would complain something like this:

Numbers.java:13: cannot find symbol
symbol : constructor Numbers()
location: class Numbers
Numbers negatives = new Numbers();
^
1 error


But the code compiles without errors and the output is -3 -1 5! Apparently the var-arg constructor matches the call with no args. The same with methods: a method go(int... x) will be executed when calling go() and there is no method go() without parameters.

Maybe this is obvious to others (to me it was not), but it might be a good idea to to include a hint on that behaviour in exam preparation books...

I really start to hate var-args...
 
Ruben Soto
Ranch Hand
Posts: 1032
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are two ways that you can call a var-args method. One of them is by supplying a list of individual arguments (and this includes passing zero arguments.) The other is to pass an array reference of the same (or a compatible) type. When you use the first method and you pass no arguments, the var-args array in the method will contain 0 elements. Also, notice that you can't pass both individual elements and an array at the point of the call (only pass either individual elements, or an array, but not both.)
 
reji singh
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
good question. nice answer Ruben.

Thanks
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic