Java Glossary : clone

CMP home Java glossary home Menu no menu Last updated 2004-06-28 by Roedy Green ©1996-2004 Canadian Mind Products

Java definitions: 0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

You are here : home : Java Glossary : C words : clone.

clone
It can sometimes be faster to make a copy of an existing object than to create a new one and initialise it. The method to do this is called clone(). If you want to make objects of your class publicly cloneable, you need code like this:

class Rabbit implements Cloneable
   {
  ...
   public Object clone()
      {
      try
         {
         return super.clone();
         }
      catch ( CloneNotSupportedException e )
         {
         return null;
         }
      }
  ...
   } // end Rabbit

You can then use it like this:

Rabbit r1 = new Rabbit();
Rabbit r2 = (Rabbit)r1.clone();

Note: To comply with Cloneable, clone() must return an Object not a Rabbit.

Instead of using super.clone(), you could use new Rabbit() and copy the fields one by one to the new object and return the new object. Then you don't have to mess with CloneNotSupportedException.

If you were happy with a protected clone, that just blindly copied the raw bits of the object, you need not redefine your own version. Usually though, you would want a public one. Note you can't create a private or default scope clone. You can only increase the visibility when you override.

The default protected clone does a shallow copy, that is, it does not make copies of objects pointed to by the object, but it copies all fields and references in an object. If you write your own clone, you might implement a deep copy, that is, also make copies of objects pointed to, and also objects pointed to by those objects recursively. Be careful. It is easy to create a chain reaction explosion or even an endless loop with a deep copy. Clone returns an Object not the type of the thing cloned. You need to cast it back.


CMP logo
CMP_home
home
Canadian Mind Products CSS
HTML Checked!
ICRA ratings logo
mindprod.com IP:[24.87.56.253]
Your IP:[80.134.30.163]
You are visitor number 3250.
Please send errors, omissions and suggestions
to improve this page to Roedy Green.
You can get a fresh copy of this page from: or possibly from your local J: drive mirror:
http://mindprod.com/jgloss/clone.html J:\mindprod\jgloss\clone.html