Cloning an object in Java

Default featured post

In Java programming frequently occur that a clone of an object is required for a reason. However, if the class is user defined, clone method should be implemented by the programmer. For that there are two possible ways.

The first one which is the most naive is to define a method and inside of the method instantiate a new object and manually assign the values of all variables inside of the class to the new object. This solution is error-prone and tedious because if you apply any changes on the class variables for example, declare a new variable then the changes should be applied in clone function as well.

The second solution is to implement Cloneable interface and code your class function easily in few lines. Check the below code which uses Cloneable interface to implement clone method.

public class MyClass implements Cloneable {
    public int x = 0;
    public int y = 10;

    public MyClass clone() throws CloneNotSupportedException {
        return (to) super.clone();