how-to

Classes

How to implement Cloneable interface for clone() method

When your class implements Cloneable interface, you can call Object.clone() method for deep copy object ensuring.

More about deep copy of the object instance you can find here.

STEP 1

At first you must implement Cloneable interface in your class:

public class Person_Cloneable implements Cloneable {

  public Person_Cloneable() {}

  /* -- fields */

  private String name;
  private int age;

  /* -- getter and setter */

  public int getAge() {
    return age;
  }

  public String getName() {
    return name;
  }

  public void setAge(int age) {
    this.age = age;
  }

  public void setName(String name) {
    this.name = name;
  }

  /* -- override clone() method */

  @Override
  protected Object clone() throws CloneNotSupportedException {

    /* -- make copy */

    Object obj = super.clone();

    /* -- you can make changes in "obj" here */

    /* -- return object copy */

    return( obj );
  }

}

STEP 2

Now you can call clone() method for copy of your object.

/* -- create original object */

Person_Cloneable person = new Person_Cloneable();

person.setName( "Jack Howard" );
person.setAge( 35 );

/* -- make deep copy of the original object */

try {
  Person_Cloneable personNew = (Person_Cloneable) person.clone();

  System.out.println( personNew.getName() );
  System.out.println( personNew.getAge() );

} catch (CloneNotSupportedException ex) {
  Logger.getLogger(Window.class.getName()).log(Level.SEVERE, null, ex);
}

The output is:

Jack Howard
35

Primitive types of the original class instance are copied automatically. For complex types you can make your own code in overrided clone() method.