Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java constructor/method with optional parameters? [duplicate]

Possible Duplicate:
Java optional parameters

I know that in PHP if you want to call a function with less parameters you declare the function like:

function foo(int param1, int param2 = "2"); 

and now I can call foo(2) and param2 will be set to 2.

I tried to do this in a Java constructor but it seems it isn't possible. Is there a way to do this or i just have to declare two constructors?

Thanks!

like image 556
tgm_rr Avatar asked Sep 15 '11 08:09

tgm_rr


People also ask

Can a constructor have optional parameter?

The definition of a method, constructor, indexer, or delegate can specify its parameters are required or optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters. Each optional parameter has a default value as part of its definition.

How do you make an optional parameter constructor?

You can use a question mark to define optional parameters in a class constructor function. Alternatively, you can set a default value for the parameter, which will be used if a value is not provided when instantiating the class.

How do you make a constructor parameter optional in Java?

You can't have optional arguments that default to a certain value in Java. The nearest thing to what you are talking about is java varargs whereby you can pass an arbitrary number of arguments (of the same type) to a method.


1 Answers

Java doesn't have the concept of optional parameters with default values either in constructors or in methods. You're basically stuck with overloading. However, you chain constructors easily so you don't need to repeat the code:

public Foo(int param1, int param2) {     this.param1 = param1;     this.param2 = param2; }  public Foo(int param1) {     this(param1, 2); } 
like image 95
Jon Skeet Avatar answered Sep 19 '22 13:09

Jon Skeet