Reputation: 9
public class Person {
private String name;
private int birthYear;
public Person(String name) {
this.name = name;
this.birthYear = 1970;
}
public int getBirthYear() {
return this.birthYear;
}
public void setBirthYear(int birthYear) {
this.birthYear = birthYear;
}
public String toString() {
return this.name + " (" + this.birthYear + ")";
}
}
public class Example {
public static void main(String[] args) {
Person first = new Person("First");
System.out.println(first);
youthen(first);
System.out.println(first);
Person second = first;
youthen(second);
System.out.println(first);
}
public static void youthen(Person person) {
person.setBirthYear(person.getBirthYear() + 1);
}
}
My tutorial says the output will be:
First (1970)
First (1971)
First (1972)
I can follow the code up until the second Person object is created. Then I don't see why calling the youthen method on the second Person object is changing the first Person object.
The way I see it, there are two Person objects. We changed the birth year of Person first, we then copied Person first's instance variable values to Person second, and then we acted on Person second's instance variable values using the youthen method, while Person first hasn't changed since the previous method call to it. I expected the final print method to return
First (1971)
Upvotes: 0
Views: 118
Reputation: 218950
up until the second Person object is created
Nope. This code only ever creates one Person
object. Right here:
new Person("First")
At no other point is the Person
constructor invoked, so at no other point is another Person
object created. What you have are multiple references to the same Person
object:
Person second = first;
As an analogy, imagine that you have a house and you write down the address to that house on two pieces of paper. One person, using their piece of paper, goes to the house and changes something about it. (Paints it a new color, for example.) The second person then uses their piece of paper to go to the house and they see the new color. Because there's only one house, no matter how many people know its address.
To create a second Person
, re-invoke the constructor:
Person second = new Person("Second");
Upvotes: 6