Hints
This articles explained about how to clone object in java using Cloneable interface. Cloneable is a interface of java.lang package. Clone() method of Cloneable interface is used to copy entire object with data. Basically Clone object is used to avoid changing the base value by the object. Java objects are not coping object to another object. It is passing the object reference to another object.
Reference copy
Students stu1 = new Students("1001","Sarathy");
Students stu2 = stu1;
stu1 and stu2 are pointing same memory.
Copy object in java
Students stu1 = new Students("1001","Sarathy");
Students stu2 = stu1.clone();
stu1 and stu2 are pointing different memory.
|
class Students implements Cloneable {
int rno;
String student_name;
public Students(int rno,String student_name) {
this.rno = rno;
this.student_name = student_name;
}
public Students clone() throws CloneNotSupportedException {
return (Students) super.clone();
}
}
class Solution {
public static void main(String args[])throws Exception{
Students stu = new Students(1001,"Sarathy");
//stu object is not copy to stuCopy. It is passing object reference of stu to stuCopy.
Students stuCopy = stu;
//clone method name of student class can be anything, but should call super.clone();
Students stuClone = stu.clone();
stuCopy.student_name = "Ram";
//Will return same names because stuCopy and stu are pointing to same reference
System.out.println(stu.student_name+" - "+stuCopy.student_name);
stuClone.student_name = "Siva";
//Clone object will not change assigned object student name
System.out.println(stu.student_name+" - "+stuClone.student_name);
}
}
|
Output
Ram - Ram
Ram - Siva
|