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

 

 

It turns out that the Object class's clone() method refuses to work if your class doesn't implement the Cloneable interface. 

What's the Cloneable interface?

Java provides an interface Cloneable, in the package java.lang.  Here is the code that defines it (with comments removed):

package java.lang;

public interface Cloneable
{
}

That is everything you need to know about interface Cloneable!

Notice that it is a marker interface, because it contains absolutely no methods, nor anything else.

The idea is that you can only call the Object class's clone() method if your class implements this interface.  So let's do that:

public class CloneMe implements Cloneable
{
  // Constructor
  public CloneMe(Object 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
  {
    return super.clone();
  }
  
  ///// Private data /////
  private Object m_object;
  private int m_value;
}

Now, this compiles, and when you test it:

class MyObject
{
  public MyObject(String name)
  {
    m_name = name;
  }

  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();
  }
}

it produces the following output:

---CloneMe object---
Object: HashId: MyObject@923e30
Name: Monkeys
Value: 27
---CloneMe object---
Object: HashId: MyObject@923e30
Name: Monkeys
Value: 27
We've finally succeeded in cloning the object!

So we're done, right?

Nope!  Take a look at the output more carefully.  While we actually have two distinct object instances of type CloneMe, each of those instances contain an Object reference which points to a single instance of MyObject.  That's what I meant by the Object class's clone() method doing a shallow copy.  It copied the reference, not what the reference referred to.

Depending on what our class is designed to do, this may be appropriate, or it may be completely wrong.

Under what circumstances can you think of where it might be incorrect?

 

This page was last modified on 02 October, 2007