Fixing Shallow Copies
Home ] Up ] The clone() method ] Implementing clone() ] The Cloneable Interface ] [ Fixing Shallow Copies ]

 

 

So what if your class requires something more sophisticated than a simple shallow copy?

You need to put more into your class's clone method:

public class CloneMe implements Cloneable
{
  // Constructor
  public CloneMe(MyObject object, int value)
  {
    m_object = object;
    m_value = value;
  }
  
  public void print()
  {
    System.out.println("---CloneMe object---\n" + 
                       "Object:  " + m_object + 
                       "Value:   " + m_value);
  }
  
  public Object clone() throws CloneNotSupportedException
  {
    CloneMe cloned = (CloneMe) super.clone();
    cloned.m_object = (MyObject) m_object.clone();
    return cloned;
  }
  
  ///// Private data /////
  private MyObject m_object;
  private int m_value;
}

We use the Object class's clone() method to create our new object, and then add code that fixes up the shallow copy problems.  In this case, I've changed the m_object instance variable to refer to a MyObject, which I clone to create a fresh instance of that object.

This means that I had to change the implementation of MyObject to support cloning:

class MyObject implements Cloneable
{
  public MyObject(String name)
  {
    m_name = name;
  }
  
  public Object clone() throws CloneNotSupportedException
  {
    return super.clone();
  }

  public String toString()
  {
    return "HashId: " + super.toString() + "\n" +
           "Name: " + m_name + "\n";
  }

  //// Data ////
  private String m_name;
}

public class CloneMeTest
{
  public static void main(String[] args) 
                       throws CloneNotSupportedException
  {
    MyObject mo1 = new MyObject("Monkeys");
    CloneMe cm1 = new CloneMe(mo1, 27);
    cm1.print();
    CloneMe cm2 = (CloneMe) cm1.clone();
    cm2.print();
  }
}

This now produces the following output:

---CloneMe object---
Object:  HashId: MyObject@923e30
Name: Monkeys
Value:   27
---CloneMe object---
Object:  HashId: MyObject@130c19b
Name: Monkeys
Value:   27
Which, as you can see, now has references to two different MyObject instances, one for each cloned CloneMe instance.

WHEW!

 

This page was last modified on 02 October, 2007