Although @Einer's answer is correct, in java you can define a method to pass an array of some type disguised as an "uncertain number of parameters", which could be used to simulate optional parameters:
public void unMetodo(String ... argumentos){
// argumentos es un vector de String
}
When this method is called, it is done this way:
...
unMetodo("Hola", null,"Mundo"); // Podría haber más parámetros String
...
With this call the method receives the vector arguments as {"hola",null,"Mundo"}
;
If instead of String
were Object
the data type, in theory you could pass arguments of any kind (and then cast them into the method)
Something like this:
/*
Parametros: String nombre, int edad, Date fechaDeNacimiento
*/
public void metodoConParametrosOpcioneales(Object ... params){
//Defaults
String nombre = "Natalia Natalia";
int edad = -1;
Date = null;
if(params.length > 0) nombre = (String) params[0];
if(params.length > 1) edad = (int) params[1];
if(params.length > 2) nombre = (Date) params[2];
// Resto de la lógica del método
}
Then if you call us:
metodoConParametrosOpcioneales("Juan");
Within the method, only the name will be set and both age and date of birth will have the default value.
EDITION I
I do not fully understand what you mean by losing the checkup
of the type of data. As for the use, it's for something very specific
(raised in this question). Actually, it's for two types of cases,
in one I will call the method passing it an hourIndex argument and in others
I will call the method without any argument. In that sense, the response of
@Einer responds completely to that requirement.
In php there is no check of the data type of the parameters, if a function that has to receive a boolean
to do something, receives a int
it simply breaks at run time.
In java, a method like the one proposed by @Einer, is checked at compile time, if you pass a int
where you have to go a boolean
, the program does not compile.
The alternative that I am exposing works as php in that sense, you can call the function with any type of data and if it is the correct one it will give an exception in execution time.
With a specific case I wanted to say that it is not good to lose the data check and for that reason I would not use it throughout a system, in each one of the methods.
For the specific case that you mention, referring to the other question, the number of parameters is well defined as well as its type of data. So I would like @Einer.
My question is, if in
a hypothetical case is necessary to pass in some cases 1 argument, in
another 2 arguments, in another N arguments, if it is better this resp.
When the number of arguments is not fixed, wanting to emulate with a method like php works, in my opinion, this answer would be more accurate.