1/12/2018 - 4:39 AM

Copy constructor and clone() in java

Copy Constructor and clone() in java

SOURCE: StackOverflow, dzone

clone() and Cloneable interface in java could be tedious and has some issues. So in order to deep clone and object we can provide a simple copy constructor:

class DummyBean {
  private String dummy;
  private Matrix matrix;
  public DummyBean(){} //default constructor

  //copy constructor, use this to clone
  public DummyBean(DummyBean another) {
    this.dummy = another.getDummy(); // String is already immutable
    this.matrix = new Matrix(another.getMatrix()); //deep copy
  public String getDummy() {
    return dummy;
  public Matrix getMatrix() {
    return matrix;