java 深拷贝 浅拷贝

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;
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值