public class Student2 implements Cloneable { private String name; private int age; private Professor2 professor; public Student2(String name, int age, Professor2 professor) { this.name = name; this.age = age; this.professor = professor; } @Override public String toString() { return "Student2 [name=" + name + ", age=" + age + ", Professor2=" + professor.toString() + "]"; } @Override public Object clone() { Student2 o = null; try { // 在运行时,Object中的clone识别出你要复制的是哪一个对象,Object中的clone() // 然后为此对象分配空间,并进行对象的复制,将原始对象的内容一一复制到新对象的存储空间中。 o = (Student2) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } o.professor = (Professor2) professor.clone(); return o; } public static void main(String[] args) { Professor2 professor = new Professor2("beijing", 12.0); Student2 s1 = new Student2("zhangsan", 18, professor); Student2 s2 = (Student2) s1.clone(); System.out.println(s1); System.out.println(s2); System.out.println("**************************************"); s2.name = "lisi"; s2.age = 20; s2.professor.setAddress("shanghai"); s2.professor.setSalary(230.0); System.out.println(s1); System.out.println(s2); } } Student2 [name=zhangsan, age=18, Professor2=Professor2 [address=beijing, salary=12.0]] Student2 [name=zhangsan, age=18, Professor2=Professor2 [address=beijing, salary=12.0]] ************************************** Student2 [name=zhangsan, age=18, Professor2=Professor2 [address=beijing, salary=12.0]] Student2 [name=lisi, age=20, Professor2=Professor2 [address=shanghai, salary=230.0]] |