Knowledge Walls
John Peter
Pune, Maharashtra, India
Clone object in java with Example in Computer software engineer articles of One day One Thing to Know
2941 Views
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.

Example
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

Best Lessons of "One day One Thing to Know"
Top lessons which are viewed more times.
  Copyright © 2014 Knowledge walls, All rights reserved
KnowledgeWalls
keep your tutorials and learnings with KnowledgeWalls. Don't lose your learnings hereafter. Save and revise it whenever required.
Click here for more details