Java - Class Shallow cloning

What is shallow cloning?

In a shallow cloning references are copied, not the objects.

The clone() method of the Object class makes only shallow cloning by default.

A ShallowClone Class That Supports Shallow Cloning.

Demo

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

  public ShallowClone(double value) {
    this.holder.setValue(value);
  }/*w  ww .  j  ava 2  s  .  com*/

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

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

  public Object clone() {
    ShallowClone copy = null;
    try {
      copy = (ShallowClone) super.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) {
    ShallowClone sc = new ShallowClone(100.00);
    ShallowClone scClone = (ShallowClone) 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