作用:实现对象的浅复制。
源码
public interface Cloneable {
}
测试
public class Person implements Cloneable{
private String name;
private Child child;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Child getChild() {
return child;
}
public void setChild(Child child) {
this.child = child;
}
// 重写Object的clone方法
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Test {
public static void main(String[] args) {
Child child = new Child();
Person p1 = new Person();
p1.setChild(child);
p1.setName("Fei");
Person p2 = null;
try {
p2 = (Person) p1.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
System.out.println("p1的地址:"+p1.hashCode());
System.out.println("p2的地址:"+p2.hashCode());
System.out.println("p1名字的地址:"+p1.getName().hashCode());
System.out.println("p2名字的地址:"+p2.getName().hashCode());
System.out.println("p1儿子的地址:"+p1.getChild().hashCode());
System.out.println("p2儿子的地址:"+p2.getChild().hashCode());
}
}
结果:
p1的地址:366712642
p2的地址:1829164700
p1名字的地址:70506
p2名字的地址:70506
p1儿子的地址:2018699554
p2儿子的地址:2018699554