In Java the arguments are passed always by value. Unfortunately, for programmers who switched from C ++ to Java, this causes confusion because in Java they decided to call references to something that is very different from C ++ references. The reason for this is that references in Java are passed by value . This is what happens:
public class Test {
public static void main( String[] args ) {
Perro unPerro = new Perro("Lupo");
cambiarNombre(unPerro);
System.out.println( "Ahora el perro se llama : " +
unPerro.obtenerNombre() );
}
public static void cambiarNombre(Perro p) {
p = new Perro("Fifi");
}
}
In this example, unPerro.obtenerNombre()
still returns "Lupo"
. The value of the variable unPerro
is not overwritten in the method cambiarNombre
with the Perro
called "Fifi"
since the reference to the object is passed by value. This means that in the cambiarNombre
method you pass a copy of the value of the object reference Perro
found in the client method (for this case, main
). If passed by reference, then unPerro.obtenerNombre()
in main
would return "Fifi"
after calling cambiarNombre
since the reference stored in object Perro
declared in the client method has been updated.
For the name to be changed, the cambiarNombre
method should alter the status of the value of the object sent as a parameter. This is achieved as follows:
public static void cambiarNombre(Perro p) {
p.asignaNombre("Fifi");
}
That is, from the cambiarNombre
method we can change the content of Perro
that is passed to you and those changes will then be reflected in the Perro
referenced by unPerro
. But since cambiarNombre
we can not make the variable unPerro
referent to another Perro
.
The implementation of Perro
is:
public class Perro {
private String miNombre;
public Perro(String nombre) {
miNombre = nombre;
}
public String obtenerNombre() {
return miNombre;
}
public void asignaNombre(String nombre) {
miNombre = nombre;
}
}
A common source of confusion is to think that references in Java and C ++ are similar because they have the same name. This is indisputably false. You have a detailed description of this in this question and answer .
This response is a translated and modified copy of an original answer in English that is a wiki community written by erlando . And it does not necessarily reflect the opinion of erlando.