1

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.
   }
}
jle
  • 686
  • 1
  • 8
  • 24
Sc00by_d00
  • 65
  • 1
  • 11

1 Answers1

0

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.

Ricardo Costeira
  • 3,171
  • 2
  • 23
  • 23
  • could you please explain how to use clone() method to create shallow copy – Sc00by_d00 Aug 22 '18 at 14:10
  • @Sc00by_d00 you create a shallow copy in your clone() implementation by simply returning `super.clone()`. You create a deep copy by calling `super.clone()` *and then* calling `clone()` on all fields. – DodgyCodeException Aug 22 '18 at 15:41