在编程过程中,我们有时会有这样的需求:将某个对象的引用A的拷贝给引用B,B具有A中已初始化的所有信息,但同时B做的任何操作都不会影响A的值。
虽然所有对象都继承了Object类,但Object类中的clone方法是protected修饰的,没法直接调用该方法。
要想使用clone方法,必须实现Cloneable接口,然后重写clone方法。
class People implements Cloneable{
private String name;
private String sex;
private Integer age;
public People(String name,String sex,Integer age){
this.name=name;
this.sex=sex;
this.age=age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public People clone() throws CloneNotSupportedException{
return (People)super.clone();
}
}
public class Test {
public static void main(String[] args) throws CloneNotSupportedException {
People org=new People("骨哥", "男", 24);
People copy=(People)org.clone();
copy.setName("谷歌");
System.out.println(org.getName()+","+org.getSex()+","+org.getAge());
System.out.println(copy.getName()+","+copy.getSex()+","+copy.getAge());
}
}