Sara
Sara

Reputation: 633

Cloning in Java

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

Answers (1)

Yoav Gur
Yoav Gur

Reputation: 1396

clone() method is actually a shallow copying.
Here's what happens in your example:

  1. person1 has a reference to name. Let's call this reference A. reference A point to some place in the heap memory.
  2. After you copy person1 to person3, the name reference in person3 (let's call it reference B) points to the same place in the heap memory. But it is not the same reference. It's 2 different references pointing to the same place in the heap memory.
  3. When you call 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

Related Questions