Cloneable接口

基本类型:存放在栈空间中。
引用类型:存放在堆空间中。

 

如果类没有实现Cloneable接口,调用类对象的clone方法会抛出CloneNotSupportedException,Object提供的clone方法是浅度复制的。

Demo:

public class TestCloneable {

    public static void main(String[] args) throws CloneNotSupportedException {
        Name name = new Name("jack");
        Person person = new Person(name, 20);
        Person clonePerson = (Person) person.clone();
        name.setFirstName("john");
        person.setAge(18);
        System.out.println("name is:" + clonePerson.getName().getFirstName() + ",age is:" + clonePerson.getAge());
    }

}

class Name {

    private String firstName;

    public Name(String firstName) {
        this.firstName = firstName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
}

class Person implements Cloneable {

    private Name name;
    private int age;

    public Person(Name name, int age) {
        this.name = name;
        this.age = age;
    }

    public Name getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

输出结果:name is: john, age is: 20

因为clone后,clonePerson的name是引用类型,所以当原name的值变化后,clonePerson的值也会变,age是基本类型,clone后不变。(引用类似于指针,变化后指向堆中不同的地方。)

发表评论

邮箱地址不会被公开。 必填项已用*标注