Object Cloning

Java have verity of facilities in the programming, One of which is Object cloning.

For Object Cloning we first have implement the Cloneable interface and have to implement its method clone() which returns the Object type.

Object cloning is use to save the time of processing task to make exact copy of the object. We can also do it by the new keyword but it will take a lot of time in crating copy of the object. So here is the simple example of object cloning.

class Test implements Cloneable{
int x = 0;
public Object clone(){
try{
return super.clone();
}
catch(CloneNotSupportedException ex){
System.out.println(ex.getMessage());
}
return null;
}

public void setNum(int x){
this.x = x;
}
public int getNum(){
return this.x;
}
}

class TestDemo{
public static void main(String[] args){
Test origin = new Test();
origin.setNum(20);
System.out.println("before : " + origin.getNum());

Test copy = (test)origin.clone();
copy.setNum(40);

System.out.println("after copy: " + copy.getNum());
System.out.println("after origin: " + origin.getNum());


}
}

Write the above program in any text editor (recommended notepad/notepad++) save it as TestDemo.java.
Compile it by the command javac TestDemo.java and execute it by java TestDemo.

No comments:

Post a Comment