Tuesday, November 4, 2014

Shallow Copy


cloned object has own copy for primitive member but for object member, it will be shared with original object

http://www.jusfortechies.com/java/core-java/deepcopy_and_shallowcopy.php 

public class ShallowCopyTest {
   
    public static void main(String[] args) throws CloneNotSupportedException{
       
        Student stud = new Student("Jet","English");
        Student stud2 = (Student) stud.clone();
        System.out.println("student name="+stud2.getName()+" subject="+stud2.getSubject().getName());
        stud.setName("Tom");
        stud.getSubject().setName("Chinese");
        System.out.println("after original object is updated, cloned student name="+stud2.getName()+" subject="+stud2.getSubject().getName());
    }

}



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
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

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

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

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

}




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=English 

after original object is updated, cloned student name=Jet subject=Chinese

No comments:

Post a Comment