I am trying to change the reference of an object and I wrote the following code.
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
}
}
I got the following output.
the reference of foo1 is Foo@15db9742
the reference of foo2 is Foo@6d06d69c
the reference of foo1 is Foo@15db9742
the reference of foo2 is Foo@6d06d69c
the reference of foo1 is Foo@6d06d69c
the reference of foo2 is Foo@6d06d69c
the reference of foo1 is Foo@15db9742
the reference of foo2 is Foo@6d06d69c
The change
method changed the reference of foo1
from Foo@15db9742
to Foo@6d06d69c
in the change
method, but the reference of foo1
did not change in the main
method. Why?