Search code examples
javaclone

clone() method (Shallow or Deep copying)


In java books and online tutorials it is stated that Object.clone() method provides shallow copying unless Cloneable interface is used but in the code I implemented clone() method without using Cloneable interface and it is providing a deep copy instead of a shallow copy.

import java.util.GregorianCalendar;
public class test1 {

   public static void main(String[] args) {

      // create a gregorian calendar, which is an object
      GregorianCalendar cal = new GregorianCalendar();

      // clone object cal into object y
      GregorianCalendar y = (GregorianCalendar) cal.clone();

      // check if reference of y is equal to cal or not
      System.out.println(cal==y);//it's output should be true if this is a shallow copy but it is false.
   }
}

Solution

  • GregorianCalendar does implement the Cloneable interface, so it should make a deep copy.

    Edit: Java deals with references to objects only. So, in this case, since GregorianCalendar's clone method performs a deep copy, a way to copy the reference would be by assigning cal to y, i.e., y = cal.