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

 

 

In principle, you can clone an object by calling the object's clone() method. 

There is a clone() method defined in the Object class, from which every other class extends.   Its signature is basically:

Object clone()

It returns a reference to the cloned Object.  It can't return anything more specific, because it doesn't know, a priori, what kind of object it's dealing with.

Note: Using the clone() method is a way of creating an object without using a constructor.  You need to be aware of this, because if you place code to perform sanity checks in your class constructors, using clone will bypass those checks!

Making a Class Cloneable

Let's imagine we have a class that we want to be able to clone itself.  Let's call it CloneMe:

public class CloneMe
{
  // 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);
  }
  
  ///// Private data /////
  private Object m_object;
  private int m_value;
}

This compiles fine, so let's see what happens when we try to clone 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)
  {
    MyObject mo1 = new MyObject("Monkeys");
    CloneMe cm1 = new CloneMe(mo1, 27);
    cm1.print();
    CloneMe cm2 = (CloneMe) cm1.clone();
    cm2.print();
  }
}

When we try to compile the above source file, Java refuses to compile it. It produces the following compile-time error message:

"CloneMeTest.java": clone() has protected access 
     in java.lang.Object at line 25, column 33

I've highlighted the offending piece of code in red.

The reason is exactly as described in the error message:  the clone method defined in class Object has protected access, which means that only subclasses of Object may call that method.

Why is it implemented this way?

Because the Object class doesn't know anything about your class, so it doesn't really know how to clone an object of your class.  The most it can do is do what's known as a shallow copy of your class's data members, which isn't always appropriate, depending on what you class does.  The implementers wanted to be sure that programmers would understand that a shallow copy isn't sufficient in many cases.

So what do we do?  We have to explore a bit more...

 

This page was last modified on 02 October, 2007