Cloning of Objects Using clone() in Java

java.lang.Object class provides a native method clone(). Calling this method on your object will return a clone of that object.”Clone” here means what in normal world the word “clone” means. A clone object is another object having same attribute values as the original object.Here is the how to do cloning of objects:

public class ClassToClone implements Cloneable {
int i;
public ClassToClone(int i)
{
this.i=i;
}
protected Object clone()
{
try
{
return super.clone();
}
catch(CloneNotSupportedException e)
{
return null;
}
} //end of clone method
}//end of class

clone() in Object has protected access. So we have to override the clone() and call super.clone() from it(As Object is superclass of every class). To ensure that our class is cloneable, i.e. it supports cloning functionality, it has to implement java.lang.Cloneable interface.Cloneable inteface does not have any method inside it.It is just a markup interface, used to tell other classes that our class supports cloning.
Now a small note on how it works.When clone() of Object class is called on an object, a new object is created of that class and all the attribute’s values are copied from original to new object.
Now because these two objects are different,calling (obj1==obj2) will give false.
Here and here is a great article about object cloning.

Advertisements

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: