Java浅谈clone
本文最后更新于:2 年前

主要是java浅克隆和深克隆的区别和实现。
(内容丢失)
Student对象(浅克隆)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| package clone;
public class Student implements Cloneable {
public int id; public String name; public Student student; public void sayName() { System.out.println(this.name); System.out.println(this.student.name); } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } public Student() { } public Student(String name) { this.name = name; } public void setName(String name) { this.name = name; } public void setStudent(Student student) { this.student = student; } }
|
测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| package clone;
public class StudentText {
public static void main(String[] args) throws CloneNotSupportedException { Student a = new Student(); a.setName("张三"); a.setStudent(new Student("学孙1")); System.out.println("学生a:"); a.sayName(); Student b = (Student) a.clone(); System.out.println("学生b:"); b.sayName(); } }
|