Java Clone, Shallow Copy and Deep Copy

Last modified on September 30th, 2014 by Joe.

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.

Marilyn-Monroe

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

Comments on "Java Clone, Shallow Copy and Deep Copy"

  1. Matt says:

    Great work Joe! Your are nicely mixing technology and humor. Its an interesting read.

  2. Evan Heather says:

    In your example source code, why is a block of code commented? Any particular meaning for that? It will help if you add a comment!

  3. Joe says:

    Commented part does the same work done by super.clone() – just to showcase that I have added that in comment.

  4. […] 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. […]

  5. som says:

    what 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.

  6. Joe says:

    Som, 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.

  7. som says:

    That 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?

  8. Joe says:

    Application 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.

  9. manoj says:

    useful article and thanks for posting it
    Can 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.”

  10. Anonymous says:

    three disadvantage given is cool…

    Dipanshu

  11. Rob Poole says:

    Nice, 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.

  12. piotr says:

    I 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. :)

  13. Anonymous says:

    Joe, Nice explanation about cloning.
    It would have been nice, if you had given example of deep cloning as well.

  14. Santosh says:

    Not only this concept every topic on this site is too good.

  15. Anonymous says:

    hey can any1 tell me how can we print the value of PI in java without using Math class i.e. without using Math.PI…???

  16. Snehal says:

    hey can u plz tel me how can we print d value of PI without using Math class i.e. without using Math.PI…???

  17. Satish Kumar says:

    this example is so nice and managed environment. pls helps for these line we r also java developer. thanks

  18. rajesh khore says:

    well explained sir thanks

  19. Anonymous says:

    Very Nice Explained….
    Thanks Sir.

  20. Java String says:

    […] 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 […]

  21. Anonymous says:

    what exactly is the difference between shallow cloning and deep cloning?

  22. sukhdev says:

    Excellent article, Great job

  23. Rahul Barve says:

    The cloning concept is clearly, to the point explained. Great work!! Thanks!!

  24. Mahmood Alam Siddiqui says:

    First of all I wants to say thanks for so good explanation.

  25. Manish says:

    Could you provide code for deep copy, if u can ? Thanks

  26. Shrikanth says:

    Thanks 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

  27. Velu says:

    It is nice !

  28. leena says:

    Liked the head first style

  29. Akki says:

    It would be helpful if you provide example of deep cloning

  30. prasad says:

    Nice article

  31. Jadumani says:

    Can I create singleton class as a clonable??
    If we create clone of singleton class then what is the purpose of class to make a singleton.

  32. Anonymous says:

    Very good description joe. From the above article, i can say cloning is use for making a clone object. Can you please tell me the scenario where java is actually using cloning concept.Please give some example also.

    Regards,
    Ashok

  33. Anonymous_2 says:

    I dont understand the difference of shallow and deep copy. If we copy your code and implement the deep copy clone then output will be the same. We need to add one object reference to the Employee object then we can understand the difference.

  34. manoj says:

    Really its great topic ….
    U explained nicely…. thanks a lot.
    Thanks
    manoj CITE

  35. manu says:

    hi please give one example of deep copy…
    it would be better

  36. Anonymous says:

    Deep clone : You will have to override the clone method in each of the classes that the class to be cloned is composed of.
    The below example is just to illustrate the deep clone.

    package clone;

    public class Customer implements Cloneable{

    String name;
    Order order;
    public Customer(String name, Order order) {
    super();
    this.name = name;
    this.order = order;
    }

    public Order getOrder() {
    return order;
    }

    public void setOrder(Order order) {
    this.order = order;
    }

    public String getName() {
    return name;
    }

    public void setName(String name) {
    this.name = name;
    }

    public Customer() {
    super();
    // TODO Auto-generated constructor stub
    }

    public Customer(String name) {
    super();
    this.name = name;
    }

    @Override
    public Object clone(){
    try {
    Customer clonedCustomer = (Customer)super.clone();
    clonedCustomer.setOrder((Order)order.clone());
    return clonedCustomer;
    } catch (CloneNotSupportedException e) {
    e.printStackTrace();
    }
    return null;
    }

    }

    package clone;

    public class Order implements Cloneable {

    Item item;

    public Order(Item item) {
    super();
    this.item = item;
    }

    public Item getItem() {
    return item;
    }

    public void setItem(Item item) {
    this.item = item;
    }

    @Override
    public Object clone(){
    try {
    Order clonedOrder = (Order)super.clone();
    clonedOrder.setItem((Item)item.clone());
    return clonedOrder;

    } catch (CloneNotSupportedException e) {
    e.printStackTrace();
    }
    return null;
    }

    }

    package clone;

    public class Item implements Cloneable {

    String itemName;

    public Item(String itemName) {
    super();
    this.itemName = itemName;
    }

    public String getItemName() {
    return itemName;
    }

    public void setItemName(String itemName) {
    this.itemName = itemName;
    }
    @Override
    public Object clone(){
    try {
    return super.clone();
    } catch (CloneNotSupportedException e) {
    e.printStackTrace();
    }
    return null;
    }
    }

    package clone;

    public class ShallowCloneTest {

    /**
    * @param args
    */
    public static void main(String[] args) {
    Customer cust = new Customer(“Cust001”, new Order(new Item(“Item001”)));
    System.out.println(“original object :” + cust);
    Customer cloned = (Customer)cust.clone();
    System.out.println(“cloned object :” + cloned);
    cloned.getOrder().getItem().setItemName(“Item002”);
    cloned.setName(“Cust002”);
    System.out.println(“original object :” + cust.getOrder().getItem().getItemName());
    System.out.println(“original object :”+ cust.getName());
    }

    }

  37. Anonymous says:

    Hi Joe,

    According to you and javadoc Object class clone method provides a shallow copy.

    Shallow copy is the copy which shares the same memory location. but in case of clone java creates a new object(seperate memory location) and copies all the properties of the actual object to new object. I am really very confused.

    http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#clone%28%29

    if you see this link it clearly says that clone creates shallow copy and a new object with copied properties

    but if you see this link

    http://en.wikipedia.org/wiki/Object_copy

    it says that shallow copy shares same memory location and change in one object can change state of copied object

    but when i used cloned object and changed value of actual object it did not had any impact on cloned object

    Please help…

  38. Madhav says:

    Hi Joe
    whatever Anonymous tells is valid point , even I am also getting confused to understarnd differences between deep and shallow clones , Please still more clear
    in memory locations perspective,
    but whaterver disadvantages explained are very good

  39. Satish says:

    Not that much clear ;(

  40. Sameer says:

    Can someone explain the statement with some example which says “clone prevents the use of final fields.”
    But cloned object retains the value of final fields also along with other member variables.

  41. saravana says:

    excellent posting.

  42. swati says:

    really this site gives a perfect answer … i like it..

  43. Anonymous says:

    awesome explanation….useful…i added the site to my favourites :)

    anjana..

  44. Shanthi says:

    Sameer

    clone() comes with default constructor which doesn’t have any arguments in that case its impossible to initialize final variables.

  45. Avinash says:

    ==========================================
    Since the Object class has the clone method (protected) you cannot use it in all your classes
    ==========================================

    Can you give example of a class where clone() can’t be used.
    Since Object is the super class of all java classes clone should be supported by all classes.

  46. suryaprakash says:

    Thank Joe.

    Very useful article .

  47. Swetha says:

    Well.. perfect explanation.. Thank you…

  48. Anonymous says:

    its supper example

  49. Aman says:

    Thank you Sir!
    Aman Kumar
    Bangalore

  50. Anonymous says:

    this blog is very useful..

  51. Krishan says:

    Really a nice article!

  52. Anonymous says:

    rocking joe, this blog will help us to become masters in java…

  53. Navin says:

    Hi Joe,

    Hope you are doing good.

    I am referring to the statement “Clone comes with lots of its and buts.”

    In that perhaps its is ifs ? If Yes then it can be corrected :)

    Thanks for this Cloning stuffs.

    Regards
    Navin

  54. nilesh says:

    I have a query regarding limitation of Final.
    I am using JDK7 and used parameter as below.
    private final String imFinal;
    which is initialized in constructor as
    this.imFinal = “I am final”;
    Now after cloning this object, I can print value of final parameter using cloned object.
    So it looks like there is no limitation on Final. Please clarify.

  55. mani says:

    hello sir ::::

    i want to jdbc concept in driver .how to create in 4 drivers and setting.in simple way

    plz send my mail

  56. Ravikiran Mane says:

    Just visited the page Rob pointed out :
    //interviewboard.wordpress.com/page/3/

    however, it contains hyperlinks to your blog.

    Wanted to verify if the work was plagiarized but {THANK GOD} was good to learn it’s not!

    I have been referring to various blogs of yours, thank you for your work.

    #Respect

  57. Anonymous says:

    what is difference between shallow copy and deep copy.. joe?

  58. nikhil says:

    I have a doubt a)Object class has clone method,b)Implicitly all classes extends Object class.Then why is it neccessary to implement Clonable interface.

  59. siddu says:

    super joe……………..

  60. Prasanth Pillai says:

    Manoj,

    In your singleton class, overwrite the clone method, something like this

    public Object clone(){
    throw CloneNotSupportedException();
    }

  61. Prasanth Pillai says:

    its override & not overwrite *** apologies…

  62. Java Array says:

    […] java arrays implements Cloneable and […]

  63. […] remember while using clone to copy, whether you need a shallow copy or deep copy. Decide based on your business needs. If you need a deep copy, you can use serialization as a hack […]

  64. satish kumar says:

    I like the comment “Because when you ask for a rabbit, it may g”””ive monkeys!”

  65. shiva says:

    nice brother

  66. ripon says:

    Thanks a lot! You make a complex concept very simple.

  67. Ashutosh Kumar says:

    How clone prevent use of final field

  68. Guru says:

    When implementing a singleton pattern
    if its superclass implements a public clone() method,
    to prevent our subclass from using this class’s clone() method to obtain a copy
    while overwrite clone method, Do we need to throw an exception of type CloneNotSupportedException?

    I feel if we class same static getInstance() factory method will server the purpose.

    Please correct me if my understanding is wrong.

  69. Nice Explanation joe… thanks for guidelines.

  70. sravya says:

    /*
    Employee copyObj = new Employee();
    copyObj.setDesignation(this.designation);
    copyObj.setName(this.name);
    return copyObj;
    */
    clone method does not call constructor. in the above code the first line is calling the default constructor. then how will the above code is equivalent to super.clone()? can u pls explain if i am wrong.

  71. Anil says:

    Joey,I was experimenting with your code.
    What I found that we need not to override clone method. Only implementing Cloneable interface.Then calling obj.clone will work.
    Is there any particular reason why we should override this method?

  72. sunil says:

    Joey, Cloneable interface is a marker interface and it doesnt have any methods it is just to intimate the compiler that this class is eligible for creating clone object. Even clone() is ‘Object’ class method and ‘Object’ class is super class in Class heirarchy we cannot override clone method directly it will throw CloneNotSupportedException, the main reason is to avoid making every class as Cloneable.

  73. sunil says:

    Sorry for typo, my previous post is for Anil.

  74. utkarsh says:

    Good Work..
    Good Example
    & Good Explanation..:)

  75. madhu says:

    super example sir, the way you explain is very nice, it gives me visual representation of how the flow goes, thanks lot

  76. bijna says:

    if i add some static field like age.if we using the commented section then update it in using clone object not updated in its main object.

  77. Swapnil says:

    Hi joe,

    I was reding this article to understand the ways to deep copy an object “Java Clone, Shallow Copy and Deep Copy”

    Unfortuntely in this article there is no single way mentioned to deep copy an object. Can you include at least one implementation for that here?

    It will also clear a lot of questions like what is the difference between Deep Copy and Shallow Copy.

    Thanks,
    Swapnil

  78. Uvaraj says:

    Hi Joe,
    I have edited the code that you had given,
    still I am getting the same output,
    in that case can you please explain how cloning really works.

    class Employee{
    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 class ShallowCopy {
    public static void main(String arg[]){
    Employee employee = new Employee();
    employee.setName(“Uvaraj”);
    //employee.setDesignation(“Senior Developer”);
    try {
    System.out.println(employee.getName());
    System.out.println(employee.getDesignation());
    } catch (Exception e) { System.out.println(“Cloneable should be implemented. ” + cns);
    }
    }
    }

  79. Dilip Senapati says:

    A very good explanation on the topic. Thanks Joe.

  80. Anonymous says:

    se

  81. Anonymous says:

    you have mentioned that cloning not invoke the constructor. but your code in clone method
    public Object clone() throws CloneNotSupportedException {
    /*
    Employee copyObj = new Employee();
    copyObj.setDesignation(this.designation);
    copyObj.setName(this.name);
    return copyObj;
    */
    return super.clone();
    }
    invoke the constructor.

    both statements are totally different.
    Do you have any comment.

  82. Selva says:

    This is really good example bass

  83. Selva says:

    Bass. Please tell us any one real time scenario using with clone

  84. Kailah Chandra Das says:

    In case of Shallow clone, if the primitives are copied and reference variable except String(as immutable) are reused in cloned object. So if we modify primitive values in one object,it does not reflect in another object but if we modify reference vlues in cloned object, same value also available in original object.
    From this we sure that primitives are copied and reference variable(not String) are shared or reused in cloned object.

  85. Kailah Chandra Das says:

    Cloneable interface is a marker interface having no method. The class which implement this interface get special status so that JVM can mark this class will be cloned.

  86. Anonymous says:

    YOU ROCK!
    THANKS!

  87. Rob Lewis says:

    I’m afraid I don’t understand this: “Since the Object class has the clone method (protected) you cannot use it in all your classes.”

    I thought a protected method was supposed to be accessible in all subclasses of the class that defines it.

  88. Vivek Gupta says:

    Hi Joe,

    in your post above you said :

    “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.”

    but in the implementation u shared, u also instantiated a new instance and initiated it by copying values.

    /*
    Employee copyObj = new Employee();
    copyObj.setDesignation(this.designation);
    copyObj.setName(this.name);
    return copyObj;
    */

    Isn’t that a self contradiction?

  89. Anonymous says:

    The functionality of the code in comments and super.clone() is same

  90. Ankush says:

    Yeah Kind of confusing .. Even i have the same doubt.

  91. Gaurav says:

    Hi Joe,

    I have always liked your work, but this article create many questions rather then answer.
    I went to comments to post my queries, but most of questions are already their.
    Can you please reply to queries in comments.

    P.S. Previous look and feel of your site was much better.

    Thanks
    Gaurav

Comments are closed for "Java Clone, Shallow Copy and Deep Copy".