package ioc;
/**
* @Author:zhuo
* @Date:2018/4/30 15:46
*
*/
public class VarCopyDemo {
public static void main(String[] args) {
System.out.println("\n********下面是浅拷贝内容********\n");
// 浅拷贝案例
Computer computer1 = new Computer();
computer1.name = "thinkpad-E470";
CPU core = new CPU();
computer1.cpu = core;
core.name="酷睿i5";
try {
Computer computer2 = (Computer) computer1.clone();
// 测试浅拷贝
System.out.println(computer2.name);
System.out.println(computer2.cpu.name);
// 修改computer1 name和cpu字段的值
computer1.name = "ideapad-z470";
computer1.cpu.name = "酷睿i7";
//下面来访问computer2
System.out.println(computer2.name);
System.out.println(computer2.cpu.name);
//深拷贝案例
Computer2 computer2_1 = new Computer2();
computer2_1.name = "联想小新潮7000";
ItMonitor monitor = new ItMonitor();
computer2_1.monitor =monitor;
monitor.dpi = "1920*1080";
Computer2 computer2_2 = (Computer2) computer2_1.clone();
System.out.println("\n********下面是深拷贝内容********\n");
//测试深拷贝
System.out.println(computer2_1.name);
System.out.println(computer2_1.monitor.dpi);
// 修改computer2_1的 name和monitor的值
computer2_1.name = "联想拯救者-R720";
computer2_1.monitor.dpi = "2560*1440";
//下面来访问computer2_2
System.out.println(computer2_2.name);
System.out.println(computer2_2.monitor.dpi);
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
// cpu类
class CPU{
public String name; // CPU型号
}
//显示器类
class ItMonitor implements Cloneable{
String dpi ; // 分辨率
@Override
protected Object clone() throws CloneNotSupportedException {
ItMonitor monitor = null;
monitor = (ItMonitor) super.clone();
return monitor;
}
}
class Computer implements Cloneable{
public String name; // 电脑型号
public CPU cpu; // 电脑的cpu
public ItMonitor monitor ; //电脑的显示器
@Override
public Object clone() throws CloneNotSupportedException {
//定义一个要复制的目的对象
Computer computer = null;
//利用Object的Native方法初始化这个对象
computer=(Computer) super.clone();
//返回对象
return computer;
}
}
class Computer2 implements Cloneable{
public String name; // 电脑的型号
public CPU cpu; //电脑的CPU
public ItMonitor monitor; //电脑的显示器
@Override
protected Object clone() throws CloneNotSupportedException {
Computer2 computer = null;
computer = (Computer2) super.clone();
computer.monitor = (ItMonitor) monitor.clone();
return computer;
}
}
总结:
上述的Cloneable接口为必要,虽然接口内没有方法,但是没有implements会报异常!!!
我们为了保存对象的状态信息,有时候会对其进行克隆,这个时候,如果如下例,使用 Computer c1 = new Computer();
Computer c2 = c1的话则只是多了一个句柄,可能无法满足我们的要求,而如果使用的是浅拷贝,
基本类型拷贝了一份,而引用类型,则只是拷贝了一个引用的句柄,也就是指针,拷贝的是指针地址。一旦有一个
句柄指向的对象的引用成员发生变化,则其他的拷贝也相应变化,如果想要把拷贝过的对象与原对象彻底分离,则
需要用到深拷贝,通过这种拷贝方法,对象类型的成员变量在克隆时创建了两份,所以普通类型和成员类型都分离开了