有一个Teacher类
属性:int age;String name;Student s
学生类Student
属性:int age;String name;Star s
明星类Star
属性:int age,String name
尝试深度克隆Teacher对象
结合String的不可变性,想一想String虽然是引用数据类型,需要进行深度克隆吗?
package day13.work;import java.util.zip.DeflaterOutputStream;/**有一个Teacher类属性:int age;String name;Student s学生类Student属性:int age;String name;Star s明星类Star属性:int age,String name尝试深度克隆Teacher对象结合String的不可变性,想一想String虽然是引用数据类型,需要进行深度克隆吗?*/public class test01 {public static void main(String[] args) throws CloneNotSupportedException {Teacher truesT=new Teacher(32,"小老师",new Student(18,"小学生",new Star()));Teacher cloneT=(Teacher)truesT.clone();System.out.println("truesT:"+truesT);System.out.println("cloneT:"+cloneT);System.out.println("-------------------------------------");System.out.println("truesT的学生:"+truesT.s.name+truesT.s);System.out.println("cloneT的学生:"+cloneT.name+cloneT.s);System.out.println("-------------------------------------");System.out.println("truesT的学生喜欢的明星:"+truesT.s.s);System.out.println("cloneT的学生喜欢的明星:"+cloneT.s.s);System.out.println("-------------------------------------");cloneT.name = "大老师";System.out.println("truesT的名字:"+truesT.name);System.out.println("cloneT的名字:"+cloneT.name);}}class Teacher implements Cloneable{int age;String name;Student s;public Teacher() {}public Teacher(int age, String name, Student s) {this.age = age;this.name = name;this.s = s;}@Overrideprotected Object clone() throws CloneNotSupportedException {Teacher cloneTea= (Teacher) super.clone();Student cloneStu= (Student) this.s.clone();cloneTea.s=cloneStu;return cloneTea;}}class Student implements Cloneable{int age;String name;Star s;public Student() {}public Student(int age, String name, Star s) {this.age = age;this.name = name;this.s = s;}@Overrideprotected Object clone() throws CloneNotSupportedException {return super.clone();}}class Star{int age;String name;public Star() {}public Star(int age, String name) {this.age = age;this.name = name;}}

