How does cloning work?
1 posts in topic
Flat View  Flat View

Posted By:   ashwini_iyer
Posted On:   Wednesday, May 12, 2004 05:32 AM

How does cloning work internally?

does it create a new object internally

Is it a expensive process?

How different is it from a new object creation

Re: How does cloning work?

Posted By:   Sean_Owen  
Posted On:   Wednesday, May 12, 2004 08:03 AM

If your class implements Cloneable, but you do not override clone(), then the default behavior, inherited from Object.clone(), is to create a "shallow copy" of the Object. Sun's documentation says:

The method clone for class Object performs a specific cloning operation. First, if the class of this object does not implement the interface Cloneable, then a CloneNotSupportedException is thrown. Note that all arrays are considered to implement the interface Cloneable. Otherwise, this method creates a new instance of the class of this object and initializes all its fields with exactly the contents of the corresponding fields of this object, as if by assignment; the contents of the fields are not themselves cloned. Thus, this method performs a "shallow copy" of this object, not a "deep copy" operation.

A new object is created, but not via the normal constructor mechanism -- that is an important difference from creating with "new". Object.clone() is a native method that basically creates an exact copy of the object in memory. Because of that, and the fact that it skips the constructor, it is probably faster in general, especially for large objects.

You may need to override clone() to further modify the results of calling super.clone(). This is very common.

clone() is somewhat controversial as it sneaks around normal object construction mechanisms. The Cloneable interface and its relation to Object.clone() is also a bit convoluted. Here is an excellent interview with Josh Bloch (creator of the Java Collections API among other things) on this issue. He suggests using copy constructors instead: http://www.artima.com/intv/bloch13.html I highly recommend his book "Effective Java" for interesting notes on this and several other things.

About | Sitemap | Contact