How to create a method with optional parameters in pure Java? [duplicate]

2

How do I create a method that does not need to enter all the parameters?

Ex. There is a method that asks for 5 parameters. But I intend to use only 2.

    
asked by anonymous 05.08.2016 / 12:49

2 answers

7

Some languages allow you to use optional arguments (parameters can never be optional ). Java is not one of them.

There is the possibility of creating several overloaded methods with a different set of parameters. This can be crazy because you will need, in the extreme, more than 20 methods in this case to suit all possibilities (of course you can only do a certain amount, you can eventually do 5 or even less).

Another possibility is to use variable arguments. This is quite different from optional arguments, but can be used to simulate in very specific situations. The normal thing is to use this feature only for data sequences, because you can not control the amount of arguments to be passed. To accept different types, you have to declare a type Object that is not ideal, and even then not all types will be accepted (primitives are not Object , so can Integer , but not int That is, it will not work very well.

In short, doing right does not give the language another alternative.

    
05.08.2016 / 13:10
2

As described in the bigown response. You can not do this in java. An alternative would be:

Original method:

void metodo(int arg1, String arg2, int arg3, String arg4, String arg5) {
}

You can do this here:

void metodo(int arg1, String arg2) {
    metodo(arg1, arg2, 0, "default2", "default3");
}

You will overload the original method by placing only two parameters. Then in the new method you will call the original method. This way, you will be able to pass the default values you want along with the values passed by the new method to the original method.

You can call the method like this:

metodo(100, "teste");

The overloaded method will call the original method passing the default values.

    
05.08.2016 / 14:50