Clone (κλών) is a Greek word meaning “branch”, referring to the process whereby a new plant can be created from a twig. In biology it is about copying the DNAs. In real world, if you clone Marilyn Monroe, will you get a copy of her with same beauty and characteristics? No, you will not get! This exactly applies to java also. See how java guys are good at naming technologies.

In java, though clone is ‘intended’ to produce a copy of the same object it is not guaranteed. Clone comes with lots of its and buts. So my first advice is to not depend on clones. If you want to provide a handle / method to deliver a copy of the current instance write a kind of factory method and provide it with a good documentation. When you are in a situation to use a third party component and produce copies of it using the clone method, then investigate that implementation carefully and get to know what is underlying. Because when you ask for a rabbit, it may give monkeys!
Shallow Copy
Generally clone method of an object, creates a new instance of the same class and copies all the fields to the new instance and returns it. This is nothing but shallow copy. Object class provides a clone method and provides support for the shallow copy. It returns ‘Object’ as type and you need to explicitly cast back to your original object.
Since the Object class has the clone method (protected) you cannot use it in all your classes. The class which you want to be cloned should implement clone method and overwrite it. It should provide its own meaning for copy or to the least it should invoke the super.clone(). Also you have to implement Cloneable marker interface or else you will get CloneNotSupportedException. When you invoke the super.clone() then you are dependent on the Object class’s implementation and what you get is a shallow copy.
Deep Copy
When you need a deep copy then you need to implement it yourself. When the copied object contains some other object its references are copied recursively in deep copy. When you implement deep copy be careful as you might fall for cyclic dependencies. If you don’t want to implement deep copy yourselves then you can go for serialization. It does implements deep copy implicitly and gracefully handling cyclic dependencies.
One more disadvantage with this clone system is that, most of the interface / abstract class writers in java forget to put a public clone method. For example you can take List. So when you want to clone their implementations you have to ignore the abstract type and use actual implementations like ArrayList by name. This completely removes the advantage and goodness of abstractness.
When implementing a singleton pattern, if its superclass implements a public clone() method, to prevent your subclass from using this class’s clone() method to obtain a copy overwrite it and throw an exception of type CloneNotSupportedException.
Note that clone is not for instantiation and initialization. It should not be synonymously used as creating a new object. Because the constructor of the cloned objects may never get invoked in the process. It is about copying the object in discussion and not creating new. It completely depends on the clone implementation. One more disadvantage (what to do there are so many), clone prevents the use of final fields. We have to find roundabout ways to copy the final fields into the copied object.
Clone is an agreement between you, compiler and implementer. If you are confident that you all three have good knowledge of java, then go ahead and use clone. If you have a slightest of doubt better copy the object manually.
Example source code for java clone and shallow copy
class Employee implements Cloneable {
private String name;
private String designation;
public Employee() {
this.setDesignation("Programmer");
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Object clone() throws CloneNotSupportedException {
/*
Employee copyObj = new Employee();
copyObj.setDesignation(this.designation);
copyObj.setName(this.name);
return copyObj;
*/
return super.clone();
}
}
public class CloneExample {
public static void main(String arg[]){
Employee jwz = new Employee();
jwz.setName("Jamie Zawinski");
try {
Employee joel = (Employee) jwz.clone();
System.out.println(joel.getName());
System.out.println(joel.getDesignation());
} catch (CloneNotSupportedException cnse) {
System.out.println("Cloneable should be implemented. " + cnse );
}
}
}
Output of the above program:
Jamie Zawinski Programmer





















Great work Joe! Your are nicely mixing technology and humor. Its an interesting read.
Matt on October 1st, 2009 2:09 amIn your example source code, why is a block of code commented? Any particular meaning for that? It will help if you add a comment!
Evan Heather on October 1st, 2009 2:58 pmCommented part does the same work done by super.clone() – just to showcase that I have added that in comment.
Joe on October 3rd, 2009 11:09 pm[...] Primary purpose of java serialization is to write an object into a stream, so that it can be transported through a network and that object can be rebuilt again. When there are two different parties involved, you need a protocol to rebuild the exact same object again. Java serialization API just provides you that. Other ways you can leverage the feature of serialization is, you can use it to perform a deep copy. [...]
Java Serialization&hellip on November 23rd, 2009 9:18 pmwhat is the difference between the above code and this code
Employee joel = jwz;
System.out.println(joel.getName());
System.out.println(joel.getDesignation());
Both give the same output.
som on December 6th, 2009 1:24 amSom, you have not cloned the object. That is you have not acquired a copy of the object. Instead you have assigned the reference of that object to a new variable. Eventually pointing to same memory location. Therefore you get the same output!
In my code I get the same output because java clone not only copies object meta data, it also copies value of attributes.
I suggest you an experiment! Add one more attribute to Employee class. After clone set a value to original object’s attribute. Now print new object’s attribute and see if that value is reflected. Do this in my code and then in your code. This will help to clear your doubt on java clone, shallow copy and deep copy.
Joe on December 6th, 2009 1:33 amThat was a valuable suggestion Joe. Thank you so much. I have another doubt. Can you please list some applications of shadow and deep copy or where they might be used?
som on December 6th, 2009 2:01 amApplication of shallow copy or deep copy depends on business needs. Unless your business logic explicitly needs deep copy, you can always go for shallow copy.
Joe on December 6th, 2009 10:51 amuseful article and thanks for posting it
manoj on January 22nd, 2010 9:58 pmCan you give an example for this “When implementing a singleton pattern, if its superclass implements a public clone() method, to prevent your subclass from using this class’s clone() method to obtain a copy overwrite it and throw a CloneNotSupportedException.”
three disadvantage given is cool…
Dipanshu
Anonymous on August 18th, 2010 12:03 pmNice, but it wasn’t too hard to notice that you name-dropped Jamie Zawinski in your source code (right down to using his usual Internet handle, jwz, as a variable name). Now, it’s possible you wrote this code all on your own and you thought it would be cheeky fun to name-drop someone who’s a co-founder of both Netscape and Mozilla.org, but based on my experiences, I find it more likely that the code was plagiarized from someone else’s example.
This makes me wonder what else was plagiarized, if the example code looks suspect. Again, maybe I’m wrong, but I’m just saying what it looks like to me. I’ve seen a lot of tech blogs and websites out there that recycle other people’s content as their own, often without even giving proper attribution (and in some cases charging for access to content that isn’t theirs in the first place!).
Now, if you *did* write that code… well, I hope JWZ isn’t a litigious sort of person. It’s kind of considered bad form to drop someone else’s name in sample code, unless you have a close relationship with that person and/or you have some kind of rivalry with them.
Now, as to your article’s contents…
“When implementing a singleton pattern, if its superclass implements a public clone() method, to prevent your subclass from using this class’s clone() method to obtain a copy overwrite it and throw a CloneNotSupportedException.”
The word here is override, not overwrite. Big difference in semantics.
“One more disadvantage with this clone system is that, most of the interface / abstract class writers in java forget to put a public clone method.”
They didn’t “forget” to do it. The clone method belongs to the Object class, and must be overridden. Abstract classes will have this method inherited from Object, but it’s a protected method, and the abstract class — by definition — won’t have all details implemented that a concrete subclass has. The point is, an abstract superclass would need to know implementation details of concrete subclasses, which is a big no-no, just in order to implement clone(). Better to defer that implementation to the concrete subclass, which may possess fields and other methods not present in the abstract superclass.
By the same token, it should now be obvious why an interface can not contain clone() as a method — first, there is already a protected clone() method in Object which you must override, and secondly, the Cloneable interface is what marks an object as being capable of being cloned, but an interface (the hypothetical interface we’re talking about, not the Cloneable interface) can’t make guarantees about the implementation logic of classes that implement it. The implementing class still needs to override Object.clone() no matter what.
Rob Poole on August 23rd, 2010 8:06 pmI found the above text on this page: //interviewboard.wordpress.com/page/3/
Someone is plagiarising. Thanks for that, otherwise I would not find this information. :)
piotr on September 11th, 2010 4:25 pmJoe, Nice explanation about cloning.
Anonymous on December 20th, 2010 7:11 amIt would have been nice, if you had given example of deep cloning as well.
Not only this concept every topic on this site is too good.
Santosh on April 28th, 2011 9:28 amhey can any1 tell me how can we print the value of PI in java without using Math class i.e. without using Math.PI…???
Anonymous on May 2nd, 2011 5:10 pmhey can u plz tel me how can we print d value of PI without using Math class i.e. without using Math.PI…???
Snehal on May 2nd, 2011 5:12 pmthis example is so nice and managed environment. pls helps for these line we r also java developer. thanks
Satish Kumar on June 15th, 2011 5:59 amwell explained sir thanks
rajesh khore on November 6th, 2011 11:18 amVery Nice Explained….
Anonymous on November 16th, 2011 9:35 amThanks Sir.
[...] but do we know why java String is immutable? Main reason behind it is for better performance. Creating a copy of existing java String is easier as there is no need to create a new instance but can be easily [...]
Java String&hellip on November 21st, 2011 1:34 amwhat exactly is the difference between shallow cloning and deep cloning?
Anonymous on November 23rd, 2011 10:42 amExcellent article, Great job
sukhdev on December 2nd, 2011 2:36 pmThe cloning concept is clearly, to the point explained. Great work!! Thanks!!
Rahul Barve on December 3rd, 2011 12:51 amFirst of all I wants to say thanks for so good explanation.
Mahmood Alam Siddiqui on December 7th, 2011 7:19 amCould you provide code for deep copy, if u can ? Thanks
Manish on December 18th, 2011 2:35 pmThanks for the detailed one on clone. Where cloning (shallow or deep) is used ? Any one practical situation or business need demanding cloning ? Please give situation.
Very much thanks for yours Java Blogs.
Thanks,
Shrikanth on December 23rd, 2011 9:50 amShrikanth
It is nice !
Velu on December 28th, 2011 8:21 amLiked the head first style
leena on January 20th, 2012 1:20 pmIt would be helpful if you provide example of deep cloning
Akki on February 3rd, 2012 4:23 pm