package com.yyr.clone;
//why clone? A与B是两个独立对象,但B的初始值由A对象确定的。so,clone()方法是最简单也是最高效的手段。
public class CloneTest {
public static void main(String[] args) throws CloneNotSupportedException {
Face face=new Face("yyr",18);
Face face1=(Face) face.clone();
Face face2=face;
System.out.println(face1==face);//false 对象复制(克隆) 地址是不相同的 创建新的对象
System.out.println(face2==face);//true 引用的复制 地址仍然是相同的 是指向同一个对象
//注意:clone方法执行的是浅拷贝
String result=face.getName()==face1.getName()?"clone是浅拷贝":"clone是深拷贝";
System.out.println(result);//clone是浅拷贝
/** 深克隆
* 1.拷贝对象实现Cloneable接口,实现clone()方法【Body类】
* 2.在clone方法内部,把该对象引用的其他对象也要clone一份【Body类 clone()方法】
* 3.被引用的对象也要实现Cloneable接口,实现clone()方法【Head类】
*/
Body body=new Body(new Head(new Face()));
Body body1=(Body) body.clone();
System.out.println("body==body1:"+(body==body1));//false
System.out.println("body.head==body1.head:"+(body.head==body1.head));//false
}
static class Body implements Cloneable{
public Head head;
public Body(){}
public Body(Head head){this.head=head;}
@Override
protected Object clone() throws CloneNotSupportedException {
Body newbody= (Body) super.clone();
newbody.head=(Head) head.clone();
return newbody;
}
}
static class Head implements Cloneable{
public Face face;
public Head(){}
public Head(Face face){this.face=face;}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
static class Face implements Cloneable{
private String name;
private int age;
public Face() {
super();
}
public Face(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Face [name=" + name + ", age=" + age + "]";
}
@Override
protected Object clone() throws CloneNotSupportedException {
return (Face)super.clone();
}
}
}