0

This is the way I understand object cloning with an example :

import java.util.GregorianCalendar;

public class CloneType1 {

  public static void main(String[] args) {
    GregorianCalendar obj = new GregorianCalendar();
    GregorianCalendar objCopy = (GregorianCalendar) obj.clone();

    System.out.println(obj.getTime());
    System.out.println(objCopy.getTime());
  }
}

Is there any benefit of using this way of implementing cloning:

public class UsingCloneable implements Cloneable {
  int rollno;
  String name;

  public UsingCloneable(int rollno,String name) {
    this.rollno=rollno;
    this.name=name;
  }
  public Object clone()throws CloneNotSupportedException{
    return super.clone();
  }

  public static void main(String[] args) {
    try {
      UsingCloneable obj = new UsingCloneable(45, "SuperMan");
      UsingCloneable objCopy = (UsingCloneable) obj.clone();

      System.out.println(obj.name+"\t"+obj.rollno);
      System.out.println(objCopy.name+"\t"+objCopy.rollno);
    } catch (CloneNotSupportedException e) {
      e.printStackTrace();
    }
  }
}
ThisaruG
  • 3,222
  • 7
  • 38
  • 60
CoDerus
  • 151
  • 1
  • 1
  • 4

1 Answers1

1

Is there any benefit of using this way of implementing cloning

just returning Object.clone() (or super.clone()) in your implementation will not make much sense. What you need to do there instead is to create new instances of all mutable fields, and set those as fields of newly instantiated object of yours. Let's add one more field to your example:

public class UsingCloneable implements Cloneable {
   int rollno;
   String name;
   List list;

If you don't deep-clone the list field, changing the contents of the list will apply both to original and clones. Here's the possible implementation

public UsingCloneable clone()throws CloneNotSupportedException{
    UsingCloneable clone = new UsingCloneable (rollno, name);
    clone.list = new ArrayList(list);
    return clone;
}

Basically all the mutable types need to be deep-cloned, otherwise you'll share their instances in-between clones

  • 1
    Strings are immutable - so no problem there: you still have a point about references to mutable objects – Mikey Jan 05 '16 at 09:45
  • Even being immutable in case a String represents an internal state of Object sharing a link to the same String will change the state of all the clones+original - not the behavior you expect after cloning – Роман Гуйван Jan 05 '16 at 09:46