java 深拷贝 浅拷贝

来源:互联网 发布:windows hadoop 编辑:程序博客网 时间:2024/05/03 00:22

1、Object类有一个保护接口,但是继承之后重写也无法使用,必须继承Cloneable接口,以下是关于深浅拷贝的测试代码:

package com.busymonkey.test;public class son implements Cloneable {private String name;public String getName() {return name;}public void setName(String name) {this.name = name;}public Object clone() {Object out = null;try {out = super.clone();} catch (CloneNotSupportedException e) {e.printStackTrace();}return out;}}


package com.busymonkey.test;public class Test implements Cloneable {private String name;private String text;public son p = new son();    public static void main(String[] args) {    Test test1 = new Test("name1","111");    test1.p.setName("wahaha");    Test test2 = null;test2 = (Test)test1.clone();    test2.setName("name2");    test2.setText("222");    test2.p.setName("yeah");    System.out.println(test1.getName()+" : "+test1.getText()+" : "+test1.p.getName());    System.out.println(test2.getName()+" : "+test2.getText()+" : "+test2.p.getName());    }    public Object clone() {    Test out = null;    try {out = (Test) super.clone();} catch (CloneNotSupportedException e) {e.printStackTrace();}    //out.p = (son)p.clone();//深拷贝    return out;    }    public Test(String name, String text) {super();this.name = name;this.text = text;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getText() {return text;}public void setText(String text) {this.text = text;}}


0 0
原创粉丝点击