介绍

实现Cloneable接口

重写Object类的clone()方法,不是Cloneable接口的方法

注意深拷贝和浅拷贝

作用:当两个对象差异较小,可以复制对象再修改,避免new再一个个设置属性

写法1

@Override
public Object clone(){
    Person person=null;
    try {
        person=(Person)super.clone();
        person.name=this.name;
        person.weight=this.weight;
        person.height=this.height;
        person.age=this.age;
    } catch (CloneNotSupportedException e) {
        e.printStackTrace();
    }
    return person;
}

写法2

public Person(Person person){
    this.name=person.name;
    this.weight=person.weight;
    this.height=person.height;
    this.age=person.age;
    this.hobbies= new ArrayList<String>(hobbies);
}
@Override
public Object clone(){
    return new Person(this);
}

实例

Android的Bundle和Intent。

OkHttp的OkHttpClient

results matching ""

    No results matching ""