1. 程式人生 > >堅持,讓夢想閃耀!

堅持,讓夢想閃耀!

以下程式碼是淺克隆:

public class User implements Cloneable {

    private Integer age;
    private String name;


    public User() {
    }

    public User(Integer age) {
        this.age = age;
    }

    public User(Integer age, String name) {
        this.age = age;
        this.name = name;
    }

    public User clone() throws CloneNotSupportedException{
        return (User)super.clone();
    }

    @Override
    public String toString() {
        return "User{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }

    public Integer getAge() {
        return age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}
//屬性也clone過來了
        User u2 = new User();
        u2.setAge(10);
        u2.setName("Tom2");
        System.out.println(u2);

        User u3 = u2.clone();
        System.out.println(u3);

        User u4 = u2.clone();
        u4.setAge(40);
        u4.setName("Tom4");
        System.out.println(u4);

        System.out.println(u2);//原物件的屬性沒變
        System.out.println(u3);//原物件的屬性沒變

輸出:

User{age=10, name='Tom2'} User{age=10, name='Tom2'} User{age=40, name='Tom4'} User{age=10, name='Tom2'} User{age=10, name='Tom2'}