现在有User类:(Getter和Setter省略)
public class User implements Cloneable { private String name; private int age; private User user; @Override public User clone() { try { return (User) super.clone(); } catch (CloneNotSupportedException e) { } return null; } }
为了测试clone方法:
public class MainTest { public static void main(String[] args) { User prop = new User(); prop.setName("prop"); User user1 = new User(); user1.setName("user1-name"); user1.setAge(10); user1.setUser(prop); User user2 = user1.clone(); user2.setName("user2-name"); user2.setAge(20); user2.getUser().setName("object change"); System.out.println(user1.getName()); System.out.println(user1.getAge()); System.out.println(user1.getUser().getName()); System.out.println(user2.getName()); System.out.println(user2.getAge()); } }
打印:
user1-name
10
object change
user2-name
20
实测证明:
1、对象要被Clone,必须implements Cloneable接口,否则运行时会报CloneNotSupportedException异常
2、对象的primitive成员变量和String成员变量是深复制,对user2的修改,不影响user1原来的值
3、对象的一般Object属性,只是浅复制,user1和user2的user成员变量引用的是堆上的同一个对象。