Java Basics (XII) - clone () method

Clone in Java is used to copy the object, by allocating a memory space of the same size and source object, and then create a new object, and then he = is the difference between what?

= Realized by copy of the object:

@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Student implements Cloneable{

    private int id;
    private String name;
    private int sex;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
} 
public static void main(String[] args) {
	Student student = new Student(1001, "sam", 1);
	Student student1 = student;
	System.out.println(student == student1);
	student1.setName("zhangsan");
	System.out.println(student.toString());
}

result:

true
Student(id=1001, name=zhangsan, sex=1)

  From the results point of view, student and student1 point to the same object, I modified the data student1, because the student point to the same object, leading to student data has changed, but

Now, I want a copy of the source object, do not want any association between the source object and the target object, we can use the clone ()

clone () implement copy of the object:

public static void main(String[] args) throws Exception{
	Student student = new Student(1001, "sam", 1);
	Student student1 = (Student)student.clone();
	System.out.println(student == student1);
	student1.setName("zhangsan");
	System.out.println(student.toString());
}

result:

false
Student(id=1001, name=sam, sex=1)

From the results point of view, we know this by clone () creates an object, and the object is not associated source

PS: Cloning an object and does not call the object's constructor

 

Be notice, next article will be written deep copy and shallow copy, including the contents of a perfect clone

Guess you like

Origin www.cnblogs.com/huigelaile/p/11031917.html