J'essaie de changer la référence d'un objet et j'ai écrit le code suivant.Java - Comment changer la référence d'une méthode?
public class Test {
public static void main(String[] args) {
Foo foo1 = new Foo();
Foo foo2 = new Foo();
System.out.println("the reference of foo1 is " + foo1);
System.out.println("the reference of foo2 is " + foo2);
System.out.println();
change(foo1, foo2);
System.out.println("the reference of foo1 is " + foo1);
System.out.println("the reference of foo2 is " + foo2);
}
public static void change(Foo foo1, Foo foo2) {
System.out.println("the reference of foo1 is " + foo1);
System.out.println("the reference of foo2 is " + foo2);
System.out.println();
foo1 = foo2;
System.out.println("the reference of foo1 is " + foo1);
System.out.println("the reference of foo2 is " + foo2);
System.out.println();
}
}
class Foo {
public Foo() {
// do nothing
}
}
J'ai obtenu la sortie suivante.
the reference of foo1 is [email protected]
the reference of foo2 is [email protected]
the reference of foo1 is [email protected]
the reference of foo2 is [email protected]
the reference of foo1 is [email protected]
the reference of foo2 is [email protected]
the reference of foo1 is [email protected]
the reference of foo2 is [email protected]
La méthode change
changé la référence de foo1
[email protected]
-[email protected]
dans la méthode change
, mais la référence de foo1
n'a pas changé dans la méthode main
. Pourquoi?
Je ne sais pas ce que vous entendez par « changer la référence d'un objet », mais je soupçonne fortement que votre question recevra une réponse [sur cette page] (https://stackoverflow.com/q/40480) - à tel point que je suis tenté de la fermer en tant que doublon. –
@Reimeus La copie marquée est incorrecte. La question concerne les références de passage. en Java, les références sont passées en tant que COPIES dans des méthodes. Toute réaffectation reste locale à cette portée uniquement. – Kon