3

Does java support constructor with default valued parameters e.g.

public Shape(int v=1,int e =2){vertices =v;edges = e; }
  • when you tried, what did you find? – Prasad Kharkar May 10 '16 at 08:49
  • 1
    No, such not supported. But you can create as many constructors as you need, with different argument number and types, e.g. no-arg `public Shape()` will call `this(int, int)` with default values. Also you can create a vararg constructor if number of arguments vary. – Alex Salauyou May 10 '16 at 08:49
  • 2
    Next time: do some prior research. Especially when you are new to a language: consider that 99,999% of all reasonable "beginner" questions have been asked here ... probably countless times. No need to add another duplication. – GhostCat May 10 '16 at 08:53
  • 3
    Well it's been 7 minutes so far and nobody has found a reasonable duplicate. The one mooted is not for constructors where the solution is quite different. Don't be too harsh on new users. Questions are the life blood of this site and I think this one is reasonable. – Bathsheba May 10 '16 at 08:56

2 Answers2

4

No, Java doesn't support default values for parameters. You can overload constructors instead:

public Shape(int v,int e) {vertices =v; edges = e; }
public Shape() { this(1, 2); }
Carlo
  • 1,450
  • 1
  • 8
  • 21
2

No it doesn't. Java doesn't support default arguments in any function; constructors included.

What you can do though is define public Shape(int v, int e) and also a default constructor

public Shape()
{
    this(1, 2);
}

Note the special syntax here to delegate the construction to the two-argument constructor.

Bathsheba
  • 220,365
  • 33
  • 331
  • 451