7

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

public Shape(int v=1,int e =2){vertices =v;edges = e; }
4
  • when you tried, what did you find? Commented May 10, 2016 at 8: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. Commented May 10, 2016 at 8: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. Commented May 10, 2016 at 8: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. Commented May 10, 2016 at 8:56

2 Answers 2

14

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); }
Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.