1
public class DenseVector extends AbstractVector implements Vector {

  public DenseVector(int n) { .. } 

  public DenseVector(Vector v) { .. }

  public DenseVector(double... elements) { .. }

}

Why can I call a constructor with variadic arguments without arguments?

DenseVector v = new DenseVector() // calls DoubleVector(double... elements)

AbstractVector has no manually provided constructors at all.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
Beny Bosko
  • 239
  • 1
  • 7

5 Answers5

4

Variadic arguments take any number of arguments. Including none.

If you want one or more, a common (slightly clumsy) pattern is

public DenseVector(double element, double... moreElements)
Thilo
  • 257,207
  • 101
  • 511
  • 656
1

Why can I call a constructor with variadic arguments without arguments?

You don't have the default constructor (it won't be generated) and the vararg constructor is the only option (it takes [0, n] doubles - you passed none).

DenseVector v = new DenseVector();

To call the no-arg constructor (if it was your intention), you have to define it first.

AbstractVector has no manually provided constructors at all

That's why you shouldn't have written super(...) in all the constructors referring to a non-default parent constructor.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
0

Variadic parameter allows a function (constructor in your case) to accept any number of arguments. Even if no argument is provided, the same function can be called.

Ashutosh
  • 529
  • 5
  • 15
0

variadic constructors can be called with any number of args (including 0 ) take a look Java, 3 dots in parameters

Roushan
  • 4,074
  • 3
  • 21
  • 38
0

As Java Language Specification states here:

If the method being invoked is a variable arity method m, it necessarily has n > 0 formal parameters. The final formal parameter of m necessarily has type  T[] for some T, and  m is necessarily being invoked with k  0 actual argument expressions.

k ≥ 0, means that you can pass 0 actual arguments to that method.

Przemysław Moskal
  • 3,551
  • 2
  • 12
  • 21