Reputation: 633
class Person implements Cloneable {
String firstName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Person clone() throws CloneNotSupportedException {
return (Person) super.clone();
}
}
Person p1 = new Person();
p1.setFirstName("P1 Sara");
Person p3 = new Person();
try {
p3 = (Person) p1.clone();
} catch (CloneNotSupportedException e) {
}
p3.setFirstName("cloned Sara");
System.out.println("P3 : " + p3.getFirstName());
System.out.println("P1: " + p1.getFirstName());
I have read that clone() method is actually a shallow copying. So, I assumed that when the value of a field in P3 is changed, the one in P1 would change too. But, that didn't happen. What am I missing here?
Upvotes: 4
Views: 167
Reputation: 1396
clone() method is actually a shallow copying.
Here's what happens in your example:
p3.setFirstName("cloned Sara")
, reference B is updated to point to another place in the heap memory. There is no reason for that to change the value of where reference A is pointing.Upvotes: 1