Sunday, November 9, 2014

Deep Copy

// deep copy, in clone() it creates a new object

public class DeepCopyTest {
   
    public static void main(String[] args) throws CloneNotSupportedException{
        Student student = new Student("Jet","Chinese"); // create student object
        Student student2 = student.clone(); // deep copy a new object student2
        System.out.println("student name="+student2.getName()+" subject="+student2.getSubject().getName());// print out this new object student2
        student.setName("Tom"); // change original object value
        student.getSubject().setName("English");
        System.out.println("student name="+student2.getName()+" subject="+student2.getSubject().getName()); // print out this new object value. it's changed.
               
    }

}



public class Student implements Cloneable{

    private String name;
    private Subject subject;
   
    public Student(String studentName, String subjectName) {
        this.name = studentName;
        this.subject = new Subject(subjectName);
    }

    @Override
    public Student clone() throws CloneNotSupportedException {
        Student student = new Student(name,subject.getName());
        return student ;
    }

    public String getName() {
        return this.name;
    }

    public Subject getSubject() {
        return this.subject;
    }

    public void setName(String studentName) {
        this.name = studentName;
    }

}

package deepcopy;

public class Subject {
    private String name;
   
    public Subject(String subjectName) {
        this.name = subjectName;
    }

    public String getName() {
        return name;
    }

    public void setName(String subjectName) {
            this.name = subjectName;
    }


}
OUTPUT



student name=Jet subject=Chinese
student name=Jet subject=Chinese

No comments:

Post a Comment