import java.util.*; /** * 深拷贝 * */ public class test { public static void main(String[] args){ String name = "张三"; int age = 15; Address ads = new Address(); ads.setAddress("北京"); Student stu1 = new Student(name,age,ads); Student stu2 = stu1.clone(); ads.setAddress("石家庄"); System.out.println("学生1的姓名:"+stu1.getName()+" 年龄是:"+stu1.getAge()+" 位置:"+stu1.getAds().getAddress()); System.out.println("学生2的姓名:"+stu2.getName()+" 年龄是:"+stu2.getAge()+" 位置:"+stu2.getAds().getAddress()); } } //地址类 class Address implements Cloneable{ private String address; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public Object clone(){ Address address = null; try { address = (Address) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return address; } } //学生类 class Student implements Cloneable{ private String name; private int age; private Address ads; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Address getAds() { return ads; } public void setAds(Address ads) { this.ads = ads; } public Student(String name, int age, Address ads){ this.name = name; this.age = age; this.ads = ads; } @Override public Student clone(){ Student stu = null; try { stu = (Student) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } stu.ads = (Address) ads.clone(); return stu; } } 运行结果是: 学生1的姓名:张三 年龄是:15 位置:石家庄 学生2的姓名:张三 年龄是:15 位置:北京 学生2进行了深拷贝, 所以位置没有发生变化。