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

Asked

Viewed 4,863 times

2

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

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

  • Either this is what is suggested in the duplicate, or using overload in the same method with fewer parameters. The duplicate’s answer I believe answers that question

  • you can overload a method or pass only one parameter as array and in that array have the arguments.

  • Did the answer solve what you were looking to know? Do you think you can accept it now? If not, you need something else to be improved?

2 answers

7

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

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

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

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

  • Varargs would not be an alternative either?

  • 3

    @diegofm is written in the answer, is an alternative but not very good.

  • And if you create a Wrapper class?

  • 1

    @Matheus I don’t know how this could help, but even if it does, it would be too complicated for little help, possibly misrepresenting the intent.

2

As described in Maniero’s reply there is no way to do this in Java. An alternative would be the following:

Original method:

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

You can do it 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 created method you will call the original method. This way, you will be able to pass to the original method the values default you want, along with the values passed per parameter in the new method.

You can call the method this way:

metodo(100, "teste");

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

  • What I call this method?

  • @Emersonbarcellos edited the answer. See if now got better.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.