{"id":2802,"date":"2018-04-10T04:50:43","date_gmt":"2018-04-10T04:50:43","guid":{"rendered":"http:\/\/codethataint.com\/blog\/?p=2802"},"modified":"2018-04-10T11:48:45","modified_gmt":"2018-04-10T11:48:45","slug":"everything-about-cloning-java","status":"publish","type":"post","link":"https:\/\/codethataint.com\/blog\/everything-about-cloning-java\/","title":{"rendered":"Everything about Cloning Java"},"content":{"rendered":"<p>Object cloning refers to creation of shallow copy of an object.<\/p>\n<p><strong>Why we Need Clone?<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n\/\/ Java program to demonstrate that assignment\r\n\/\/ operator only creates a new reference to same\r\n\/\/ object.\r\nimport java.io.*;\r\n \r\n\/\/ A test class whose objects are cloned\r\nclass Test\r\n{\r\n    int x, y;\r\n    Test()\r\n    {\r\n        x = 10;\r\n        y = 20;\r\n    }\r\n}\r\n \r\n\/\/ Driver Class\r\nclass Main\r\n{\r\n    public static void main(String&#x5B;] args)\r\n    {\r\n         Test ob1 = new Test();\r\n \r\n         System.out.println(ob1.x + &quot; &quot; + ob1.y);\r\n \r\n         \/\/ Creating a new reference variable ob2\r\n         \/\/ pointing to same address as ob1\r\n         Test ob2 = ob1;\r\n \r\n         \/\/ Any change made in ob2 will be reflected\r\n         \/\/ in ob1\r\n         ob2.x = 100;\r\n \r\n         System.out.println(ob1.x+&quot; &quot;+ob1.y);\r\n         System.out.println(ob2.x+&quot; &quot;+ob2.y);\r\n    }\r\n}\r\n<\/pre>\n<p><strong>output<\/strong><\/p>\n<pre>\r\n10 20\r\n100 20\r\n100 20\r\n<\/pre>\n<p>In Java, we can create only copy of reference variable and not the object.<\/p>\n<p><strong>How to Use Clone?<\/strong><\/p>\n<ol>\n<li>class that implements clone() should call super.clone() to obtain the cloned object reference<\/li>\n<li>the class must also implement java.lang.Cloneable interface whose object clone we want to create otherwise it will throw CloneNotSupportedException when clone method is called on that class\u2019s object.<\/li>\n<li>\n<pre>\r\n  protected Object clone() throws CloneNotSupportedException\r\n<\/pre>\n<\/li>\n<\/ol>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n\/\/ A Java program to demonstrate shallow copy\r\n\/\/ using clone()\r\nimport java.util.ArrayList;\r\n \r\n\/\/ An object reference of this class is\r\n\/\/ contained by Test2\r\nclass Test\r\n{\r\n    int x, y;\r\n}\r\n \r\n\/\/ Contains a reference of Test and implements\r\n\/\/ clone with shallow copy.\r\nclass Test2 implements Cloneable\r\n{\r\n    int a;\r\n    int b;\r\n    Test c = new Test();\r\n    public Object clone() throws\r\n                   CloneNotSupportedException\r\n    {\r\n        return super.clone();\r\n    }\r\n}\r\n \r\n\/\/ Driver class\r\npublic class Main\r\n{\r\n    public static void main(String args&#x5B;]) throws\r\n                          CloneNotSupportedException\r\n    {\r\n       Test2 t1 = new Test2();\r\n       t1.a = 10;\r\n       t1.b = 20;\r\n       t1.c.x = 30;\r\n       t1.c.y = 40;\r\n \r\n       Test2 t2 = (Test2)t1.clone();\r\n \r\n       \/\/ Creating a copy of object t1 and passing\r\n       \/\/  it to t2\r\n       t2.a = 100;\r\n \r\n       \/\/ Change in primitive type of t2 will not\r\n       \/\/ be reflected in t1 field\r\n       t2.c.x = 300;\r\n \r\n       \/\/ Change in object type field will be\r\n       \/\/ reflected in both t2 and t1(shallow copy)\r\n       System.out.println(t1.a + &quot; &quot; + t1.b + &quot; &quot; +\r\n                          t1.c.x + &quot; &quot; + t1.c.y);\r\n       System.out.println(t2.a + &quot; &quot; + t2.b + &quot; &quot; +\r\n                          t2.c.x + &quot; &quot; + t2.c.y);\r\n    }\r\n}\r\n<\/pre>\n<p><strong>output<\/strong><\/p>\n<pre>\r\n10 20 300 40\r\n100 20 300 40\r\n<\/pre>\n<p><strong>How to Achieve Deep Copy<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n\/\/ A Java program to demonstrate deep copy\r\n\/\/ using clone()\r\nimport java.util.ArrayList;\r\n \r\n\/\/ An object reference of this class is\r\n\/\/ contained by Test2\r\nclass Test\r\n{\r\n    int x, y;\r\n}\r\n \r\n \r\n\/\/ Contains a reference of Test and implements\r\n\/\/ clone with deep copy.\r\nclass Test2 implements Cloneable\r\n{\r\n    int a, b;\r\n \r\n    Test c = new Test();\r\n \r\n    public Object clone() throws\r\n                CloneNotSupportedException\r\n    {\r\n        \/\/ Assign the shallow copy to new refernce variable t\r\n        Test2 t = (Test2)super.clone();\r\n \r\n        t.c = new Test();\r\n \r\n        \/\/ Create a new object for the field c\r\n        \/\/ and assign it to shallow copy obtained,\r\n        \/\/ to make it a deep copy\r\n        return t;\r\n    }\r\n}\r\n \r\npublic class Main\r\n{\r\n    public static void main(String args&#x5B;]) throws\r\n                             CloneNotSupportedException\r\n    {\r\n       Test2 t1 = new Test2();\r\n       t1.a = 10;\r\n       t1.b = 20;\r\n       t1.c.x = 30;\r\n       t1.c.y = 40;\r\n \r\n       Test2 t3 = (Test2)t1.clone();\r\n       t3.a = 100;\r\n \r\n       \/\/ Change in primitive type of t2 will not\r\n       \/\/ be reflected in t1 field\r\n       t3.c.x = 300;\r\n \r\n       \/\/ Change in object type field of t2 will not\r\n       \/\/ be reflected in t1(deep copy)\r\n       System.out.println(t1.a + &quot; &quot; + t1.b + &quot; &quot; +\r\n                          t1.c.x + &quot; &quot; + t1.c.y);\r\n       System.out.println(t3.a + &quot; &quot; + t3.b + &quot; &quot; +\r\n                          t3.c.x + &quot; &quot; + t3.c.y);\r\n    }\r\n}\r\n<\/pre>\n<p><strong>output<\/strong><\/p>\n<pre>\r\n10 20 30 40\r\n100 20 300 0\r\n<\/pre>\n<p><strong>When to use Clone?<\/strong><\/p>\n<ol>\n<li>We should use clone to copy arrays because that\u2019s generally the fastest way to do it.<\/li>\n<\/ol>\n<p><strong>Disadvantages of Clone Method<\/strong><\/p>\n<ol>\n<li>Cloneable interface lacks the clone() method. Actually, Cloneable is a marker interface and doesn\u2019t have any methods in it, and we still need to implement it just to tell the JVM that we can perform clone() on our object.<\/li>\n<li>Object.clone() is protected, so we have to provide our own clone() and indirectly call Object.clone() from it.<\/li>\n<li>If we are writing a clone method in a child class, e.g. Person, then all of its superclasses should define the clone() method in them or inherit it from another parent class. Otherwise, the super.clone() chain will fail.\n<\/li>\n<li>We can not manipulate final fields in Object.clone() because final fields can only be changed through constructors. In our case, if we want every Person object to be unique by id, we will get the duplicate object if we use Object.clone() because Object.clone() will not call the constructor, and final id field can\u2019t be modified from Person.clone().<\/li>\n<\/ol>\n<p>There are two effective ways to create copy of object <\/p>\n<ol>\n<li>Copy Constructor &#8211; Refer <a href=\"https:\/\/deepeshdarshan.wordpress.com\/2013\/12\/05\/copy-constructors-in-java\/\">here<\/a><\/li>\n<li>Serialization- Refer <a href=\"https:\/\/www.javaworld.com\/article\/2077578\/learn-java\/java-tip-76--an-alternative-to-the-deep-copy-technique.html\">Here<\/a><\/li>\n<\/ol>\n<p><strong>Even copy constructor has its disadvantage since working with the internal object(Child Objects) may make it inconsistent and fragile<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Object cloning refers to creation of shallow copy of an object. Why we Need Clone? \/\/ Java program to demonstrate that assignment \/\/ operator only creates a new reference to same \/\/ object. import java.io.*; \/\/ A test class whose objects are cloned class Test { int x, y; Test() { x = 10; y&hellip; <a href=\"https:\/\/codethataint.com\/blog\/everything-about-cloning-java\/\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3],"tags":[],"class_list":["post-2802","post","type-post","status-publish","format-standard","hentry","category-java"],"_links":{"self":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/2802","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/comments?post=2802"}],"version-history":[{"count":6,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/2802\/revisions"}],"predecessor-version":[{"id":2810,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/2802\/revisions\/2810"}],"wp:attachment":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/media?parent=2802"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/categories?post=2802"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/tags?post=2802"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}