Java的clone方法

如今有User類:(Getter和Setter省略)ide

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());
    }
}

打印:spa

user1-name
10
object change
user2-name
20code

 

實測證實:對象

一、對象要被Clone,必須implements Cloneable接口,不然運行時會報CloneNotSupportedException異常blog

二、對象的primitive成員變量和String成員變量是深複製,對user2的修改,不影響user1原來的值接口

三、對象的通常Object屬性,只是淺複製,user1和user2的user成員變量引用的是堆上的同一個對象。get

相關文章
相關標籤/搜索