If you are looking for an optional parameter, use method overload.
public void teste() {
teste(false);
}
public void teste(boolean b) {
//executa ação aqui
}
This works for simple methods. I would not recommend using more than two or three versions of the same method and only when there are no more than two or three parameters involved, because the overload can lead to bizarre situations and confusion when passing the parameters.
If you have methods with multiple parameters, pass an object as a parameter implementing the Builder Pattern.
For example, instead of doing so:
void fazerPizza(boolean mussarela, boolean oregano, boolean calabreza, boolean tomate, String nome) {
//...
}
...
fazerPizza(true, false, true, false, "Calabreza");
Could stay like this:
void fazerPizza(PizzaBuilder b) {
//...
}
fazerPizza(new PizzaBuilder("Calabreza")
.mussarela()
.calabreza());
With this pattern, you can auto-complete the possible parameters without getting confused, omit what you don’t want and still leave default values on the object PizzaBuilder
if you want.
Read more on Intelligently Building Objects: Pattern Builder and Fluent Interfaces.
I believe the closest you’ll get is using varargs as explained at this link and in this one because java doesn’t allow you to pass anything to a method that expects some parameter.
– user28595
In case, I would like to leave a value attributed to it if it were not passed
– Julyano Felipe
So that’s not possible in java. If a method waits for a parameter, it must be passed, or you need to write a new method with signature without passing parameters.
– user28595