Purpose of clone() method in Object class

clone() is a method in Object class, and can be used to create duplicate object. Since Object class is base class of all classes in Java, clone() method is available in all classes. In case an object need to invoke clone() method, that class need to implement java.lang.Cloneable interface. If clone() method is invoked without implementing interface, an exception CloneNotSupportedException is being thrown, and cloning is not successful.

Clone object
Also note that below is not cloning an object, as only one object exists, but just another reference(obj1) is created, and not the actual object. Hence this cannot be considered as cloning.

Abc obj1 = new Abc();
Abc obj2 = obj1;

Below is an example, which throws CloneNotSupportedException

class Test{
	int i;
	String str;

	public Object clone()
	{
		try
		{
			return super.clone();
		}
		catch(CloneNotSupportedException ce)
		{
			ce.printStackTrace();
			return null;
		}
	}
}

public class Demo {
	public static void main(String args[])
	{
		Test obj = new Test();

		Test obj_clone = (Test)obj.clone();
	}
}

Output:

java.lang.CloneNotSupportedException: Test
	at java.lang.Object.clone(Native Method)
	at Test.clone(Demo.java:10)
	at Demo.main(Demo.java:25)


Below is right way to clone an object. As shown the class(whose objects can be successfully cloned) need to implement Cloneable interface


class Test implements Cloneable{
	int i;
	String str;

	public Object clone()
	{
		try
		{
			return super.clone();
		}
		catch(CloneNotSupportedException ce)
		{
			ce.printStackTrace();
			return null;
		}
	}
}

public class Demo {
	public static void main(String args[])
	{
		Test obj = new Test();

		obj.i = 10;
		obj.str = new String("testing");

		Test obj_clone = (Test)obj.clone();

		System.out.println("i="+obj.i+", string is "+obj_clone.str);
	}
}


Output:
i=10, string is testing
However, there can be side effects of cloning, if not used properly. As known, Cloning of an object is creation of exact binary copy of the object.

Cloneable is Marker or Tagging interface(and do not declare any methods), which just conveys JVM that objects of the Class are eligible for cloning.

You may also like to read:
printStackTrace output to a String
stack and heap storage in Java
purpose of finalize() Method
How to override toString()

One thought on “Purpose of clone() method in Object class”

Leave a Reply