How does this fragment modify the passed object?
I was doing a Java quiz and came across this question:
class Person {
static int pid;
int age;
String name;
Person(String s, int i) {
++pid;
name = s;
age = i;
}
}
class Test {
public static void main(String args[]) {
Person p1 = new Person("John", 22);
Test te = new Test();
Person p2 = te.change(p1);
System.out.println(p2.pid + " " + p2.name + " " + p2.age);
System.out.print(p1.pid + " " + p1.name + " " + p1.age);
}
private Person change(Object o) {
Person p2 = (Person) o;
p2.age = 25;
return p2;
}
}
The answer ended up being 1 John 25
printed twice, but I'm confused as to how this is going. The object reference value is p1
sent to the method change
, but the content appears to be copied into a new named object p2
. So where is it p1
really changed?
source to share
Person p1 = new Person("John", 22);
Person p2 = te.change(p1);
Now p1
has its own fields:
p1.age
is equal to 22, and p1.name
- John
.
* Variable static
pid
is shared between all objects, in this example we don't really care
Now you call change
on p2
, see what's going on:
You are passing an object p1
that is a reference by value. You are changing age
to 25, so the original object will be changed. Now p1
has the attribute age
set to 25.
Finally, you return p2;
and he will be assigned p2
to main
.
source to share