本文主要是介绍java对象克隆之深度克隆 deep clone,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
克隆技术默认的是浅度克隆,对于包含在对象内部的对象并没有克隆,例如对象stdA包含对象x,克隆后得到对象stdB,也包含对象x,但两个x所指向的数据成员相同。
深度克隆实例如下:
package com.demo;
class Book implements Cloneable{private String name;private double price;public Book(String name, double price){this.name = name;this.price = price;}public void setName(String name){this.name = name;}public Object clone() throws CloneNotSupportedException{return super.clone();}public String toString(){return "书名:"+ this.name + " 单价:" + this.price;}
}
class Student implements Cloneable{private String name;private String sex;private Book book;public Student(String name, String sex, Book book){this.name = name;this.sex = sex;this.book = book;}public Object clone() throws CloneNotSupportedException {Student std = null;//克隆当前对象std = (Student)super.clone();//克隆当前对象所包含的对象std.book = (Book)book.clone();return std;//return super.clone();}public void setName(String name){this.name = name;}public void setBook(Book book){this.book = book;}public String toString(){return "姓名:"+name + ", 性别" + sex + "\n借的书:" + this.book.toString();}
}
public class Demo {
public static void main(String[] args) throws Exception {Book book = new Book("理想国", 35);Student stdA = new Student("梅西", "男", book);//采用赋值方式Student stdB = stdA;stdA.setName("李娜");System.out.println("stdA:"+ stdA + "\nstdB:" + stdB);stdB = (Student) stdA.clone();stdA.setName("梅西");System.out.println("克隆之后:");System.out.println("stdA: " + stdA + "\nstdB " + stdB);}}
输出结果:
stdA:姓名:李娜, 性别男
借的书:书名:理想国 单价:35.0
stdB:姓名:李娜, 性别男
借的书:书名:理想国 单价:35.0
克隆之后:
stdA: 姓名:梅西, 性别男
借的书:书名:理想国 单价:35.0
stdB 姓名:李娜, 性别男
借的书:书名:理想国 单价:35.0
深度克隆步骤1.克隆当前对象;2克隆当前对象所引用的对象;3返回当前对象
这篇关于java对象克隆之深度克隆 deep clone的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!