What is the benifit of clone() method ?

Clone() is a method in java.lang.Object class which throws a checked exception as CloneNotSupportedException.
Usually you create one reference variable by assigning another one like,
Fun f = new Fun();
Fun f1 = f;
Now both f and f1 refers to the same memory location in heap area. So some change in one reflects in other.
But when you create a reference using clone() method like,
Fun f=new Fun();
Fun f2 = f.clone();
This time jvm creates the f2 object in another memory location. So now both f and f2 are in different memory. Change in one does not reflect in other.

public class Fun implements Cloneable{
int x=10;
public static void main(String[] args)throws Exception{
Fun f=new Fun();
//Without using clone
Fun f1=f;
System.out.println(f.x+" "+f1.x);
//Here both f and f1 are same

//Using clone
Fun f2=(Fun)f.clone();
System.out.println(f.x+" "+f2.x);
//Here f and f2 are different

111 111
111 222

No comments:

Post a Comment