1.实现克隆的方式
1.对象的类需要实现Cloneable接口
2.重写Object类中的clone()方法
3.根据重写的clone()方法得到想要的克隆结果,例如浅克隆与深克隆。
2.深克隆与浅克隆的区别
图解:
代码:
浅克隆:
//学生类
public class Student implements Cloneable{
private String name;
private Integer age;
private Grade grade;
public Student(String name, Integer age, Grade grade) {
this.name = name;
this.age = age;
this.grade = grade;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Grade getGrade() {
return grade;
}
public void setGrade(Grade grade) {
this.grade = grade;
}
@Override
public String toString() {
return "Student{" +
"name=‘" + name + ‘\‘‘ +
", age=" + age +
", grade=" + grade +
‘}‘;
}
@Override
protected Student clone() throws CloneNotSupportedException {
return (Student) super.clone();
}
}
//成绩类
public class Grade {
private Integer chinese;
private Integer math;
private Integer english;
public Grade(Integer chinese, Integer math, Integer english) {
this.chinese = chinese;
this.math = math;
this.english = english;
}
public Integer getChinese() {
return chinese;
}
public void setChinese(Integer chinese) {
this.chinese = chinese;
}
public Integer getMath() {
return math;
}
public void setMath(Integer math) {
this.math = math;
}
public Integer getEnglish() {
return english;
}
public void setEnglish(Integer english) {
this.english = english;
}
@Override
public String toString() {
return "Grade{" +
"chinese=" + chinese +
", math=" + math +
", english=" + english +
‘}‘;
}
@Override
protected Grade clone() throws CloneNotSupportedException {
return (Grade)super.clone();
}
}
//测试类
public class Test {
public static void main(String[] args) throws CloneNotSupportedException {
Student student = new Student("student", 18, new Grade(100, 100, 100));
Student newStudent = (Student) student.clone();
newStudent.setName("newStudent");
newStudent.setAge(20);
newStudent.getGrade().setChinese(90);
newStudent.getGrade().setEnglish(90);
newStudent.getGrade().setMath(90);
System.out.println(student);
System.out.println(newStudent);
}
}
//测试结果
Student{name=‘student‘, age=18, grade=Grade{chinese=90, math=90, english=90}}
Student{name=‘newStudent‘, age=20, grade=Grade{chinese=90, math=90, english=90}}
结论:浅克隆只克隆基本数据属性,不会克隆对象属性引用的对象(也就是不会克隆Student对象引用的Grade对象),克隆前后两个对象的引用指向同一个对象。
深克隆:
//学生类
@Override
protected Student clone() throws CloneNotSupportedException {
Student newStudent = (Student) super.clone();
Grade grade = (Grade) newStudent.getGrade().clone();
newStudent.setGrade(grade);
return newStudent;
}
//测试结果
Student{name=‘student‘, age=18, grade=Grade{chinese=100, math=100, english=100}}
Student{name=‘newStudent‘, age=20, grade=Grade{chinese=90, math=90, english=90}}
结论:深克隆不仅克隆基本数据属性,还会克隆对象属性引用的对象(在Student类的clone()方法中再克隆一次Grade对象)