devxlogo

Reference Assignment vs. Cloning

Reference Assignment vs. Cloning

In Java, the reference to an existing reference obtained by assignment is just a duplicate reference to the object (and not to a copy of the object). The reference that is returned by cloning an object is a new reference to a copy of the object. The following code illustrates the difference between reference assignment and cloning:

 1.   public class TestClone {2.     public static void main(String[] args) {3.       CloneableClass r1 = new CloneableClass();4.       CloneableClass r2 = r1;5.       CloneableClass r3 = null;6. 7.       try {8.         r3 = (CloneableClass)(r1.clone());9.       }10.    catch (CloneNotSupportedException cnse) {11.       System.out.println("This class doesn't support cloning");12.    }13.     System.out.println("id1 = " + r1.id + ", id2 = " + r2.id + ",14.                         id3 = " + r3.id);15. 16.   r2.id = "Original";17.   r3.id = "Copy";18. 19.   System.out.println("id1 = " + r1.id + ", id2 = " + r2.id + ", 20.                      id3 = " + r3.id);21.   }22. }23. 24. class CloneableClass extends TestClone implements Cloneable {25.   public String id = "Default";26. }

The output obtained on running this code is:

 id1 = Default, id2 = Default, id3 = Defaultid1 = Original, id2 = Original, id3 = Copy

Lines 24-26 define a class called CloneableClass that has a single attribute: a String called id. Notice that it extends Cloneable. This is a requirement for any class on which the clone() method can be called. Line 3 obtains a reference (r1) to a new instance of the Cloneable class. Line 4 copies that reference into r2. Lines 5-12 assign a clone of the object to reference r3. The clone() method is actually called on Line 8.

On Lines 13-14, the values of the “id” field of all three references are printed out. The first line of the output just displays the string “Default” for all three. On Line 16, r2’s id field is changed to a new string “Original.” On Line 14, r3’s id field is changed to “Copy.” The second line of output shows that the values of the “id” fields of r1 and r2 are “Original” while the id field of r3 changes to “Copy.” Thus, the change applied to the object referenced by r2 changes the object referenced by r1. This is because r1 and r2 point to the same object. However, the change applied to the object referenced by r3 does not affect the object referenced by r1 and r2. This is because r3 refers to a clone of the original object.

See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist