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!
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.
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.
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.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With