Java - Class Deep cloning

What is deep cloning?

Deep cloning would clone all objects referenced by all reference instance variables of an object.

Deep cloning implementation

The shallow cloning is performed by calling the clone() method of the Object class.

Then you will need to write code to clone all reference instance variables.

A DeepClone Class That Performs Deep Cloning

Demo

class DeepClone implements Cloneable {
  private DoubleHolder holder = new DoubleHolder(0.0);

  public DeepClone(double value) {
    this.holder.setValue(value);
  }//from w ww .j  av a2  s . c  o m

  public void setValue(double value) {
    this.holder.setValue(value);
  }

  public double getValue() {
    return this.holder.getValue();
  }

  public Object clone() {
    DeepClone copy = null;
    try {
      copy = (DeepClone) super.clone();

      // Need to clone the holder reference variable too
      copy.holder = (DoubleHolder) this.holder.clone();
    } catch (CloneNotSupportedException e) {
      e.printStackTrace();
    }

    return copy;
  }
}

class DoubleHolder implements Cloneable {
  private double value;

  public DoubleHolder(double value) {
    this.value = value;
  }

  public void setValue(double value) {
    this.value = value;
  }

  public double getValue() {
    return this.value;
  }

  public Object clone() {
    DoubleHolder copy = null;
    try {
      copy = (DoubleHolder) super.clone();
    } catch (CloneNotSupportedException e) {
      e.printStackTrace();
    }
    return copy;
  }
}

public class Main {
  public static void main(String[] args) {
    DeepClone sc = new DeepClone(100.00);
    DeepClone scClone = (DeepClone) sc.clone();

    // Print the value in original and clone
    System.out.println("Original:" + sc.getValue());
    System.out.println("Clone :" + scClone.getValue());

    sc.setValue(200.00);

    // Print the value in original and clone
    System.out.println("Original:" + sc.getValue());
    System.out.println("Clone :" + scClone.getValue());
  }
}

Result

Related Topic