Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructors with default values of parameters [duplicate]

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

public Shape(int v=1,int e =2){vertices =v;edges = e; }
like image 917
Kaustubh Olpadkar Avatar asked Feb 07 '23 01:02

Kaustubh Olpadkar


2 Answers

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); }
like image 106
Carlo Avatar answered Feb 10 '23 09:02

Carlo


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.

like image 28
Bathsheba Avatar answered Feb 10 '23 11:02

Bathsheba