有一个Teacher类
    属性:int age;String name;Student s
    学生类Student
    属性:int age;String name;Star s
    明星类Star
    属性:int age,String name
    尝试深度克隆Teacher对象
    结合String的不可变性,想一想String虽然是引用数据类型,需要进行深度克隆吗?

    1. package day13.work;
    2. import java.util.zip.DeflaterOutputStream;
    3. /**有一个Teacher类
    4. 属性:int age;String name;Student s
    5. 学生类Student
    6. 属性:int age;String name;Star s
    7. 明星类Star
    8. 属性:int age,String name
    9. 尝试深度克隆Teacher对象
    10. 结合String的不可变性,想一想String虽然是引用数据类型,需要进行深度克隆吗?*/
    11. public class test01 {
    12. public static void main(String[] args) throws CloneNotSupportedException {
    13. Teacher truesT=new Teacher(32,"小老师",new Student(18,"小学生",new Star()));
    14. Teacher cloneT=(Teacher)truesT.clone();
    15. System.out.println("truesT:"+truesT);
    16. System.out.println("cloneT:"+cloneT);
    17. System.out.println("-------------------------------------");
    18. System.out.println("truesT的学生:"+truesT.s.name+truesT.s);
    19. System.out.println("cloneT的学生:"+cloneT.name+cloneT.s);
    20. System.out.println("-------------------------------------");
    21. System.out.println("truesT的学生喜欢的明星:"+truesT.s.s);
    22. System.out.println("cloneT的学生喜欢的明星:"+cloneT.s.s);
    23. System.out.println("-------------------------------------");
    24. cloneT.name = "大老师";
    25. System.out.println("truesT的名字:"+truesT.name);
    26. System.out.println("cloneT的名字:"+cloneT.name);
    27. }
    28. }
    29. class Teacher implements Cloneable{
    30. int age;
    31. String name;
    32. Student s;
    33. public Teacher() {
    34. }
    35. public Teacher(int age, String name, Student s) {
    36. this.age = age;
    37. this.name = name;
    38. this.s = s;
    39. }
    40. @Override
    41. protected Object clone() throws CloneNotSupportedException {
    42. Teacher cloneTea= (Teacher) super.clone();
    43. Student cloneStu= (Student) this.s.clone();
    44. cloneTea.s=cloneStu;
    45. return cloneTea;
    46. }
    47. }
    48. class Student implements Cloneable{
    49. int age;
    50. String name;
    51. Star s;
    52. public Student() {
    53. }
    54. public Student(int age, String name, Star s) {
    55. this.age = age;
    56. this.name = name;
    57. this.s = s;
    58. }
    59. @Override
    60. protected Object clone() throws CloneNotSupportedException {
    61. return super.clone();
    62. }
    63. }
    64. class Star{
    65. int age;
    66. String name;
    67. public Star() {
    68. }
    69. public Star(int age, String name) {
    70. this.age = age;
    71. this.name = name;
    72. }
    73. }

    image.png