- 浅克隆:复制对象的引用地址,导致克隆对象和原始对象共享引用类型字段的实际对象。
-
class Person implements Cloneable { String name; Address address; public Person(String name, Address address) { this.name = name; this.address = address; } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } } class Address { String city; public Address(String city) { this.city = city; } } public class Main { public static void main(String[] args) throws CloneNotSupportedException { Address address = new Address("New York"); Person person1 = new Person("Alice", address); Person person2 = (Person) person1.clone(); System.out.println(person1.name); // Alice System.out.println(person2.name); // Alice System.out.println(person1.address.city); // New York System.out.println(person2.address.city); // New York person2.address.city = "Los Angeles"; System.out.println(person1.address.city); // Los Angeles (说明 address 引用被共享) System.out.println(person2.address.city); // Los Angeles } }
- 深克隆:复制引用类型字段所指向的实际对象,使得克隆对象和原始对象完全独立。
-
class Person implements Cloneable { String name; Address address; public Person(String name, Address address) { this.name = name; this.address = address; } @Override protected Object clone() throws CloneNotSupportedException { Person cloned = (Person) super.clone(); cloned.address = (Address) address.clone(); // 深拷贝 address return cloned; } } class Address implements Cloneable { String city; public Address(String city) { this.city = city; } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } } public class Main { public static void main(String[] args) throws CloneNotSupportedException { Address address = new Address("New York"); Person person1 = new Person("Alice", address); Person person2 = (Person) person1.clone(); System.out.println(person1.name); // Alice System.out.println(person2.name); // Alice System.out.println(person1.address.city); // New York System.out.println(person2.address.city); // New York person2.address.city = "Los Angeles"; System.out.println(person1.address.city); // New York (说明 address 引用被独立复制) System.out.println(person2.address.city); // Los Angeles } }