java对象克隆的方法_Java中,对象克隆,使用Object中的方法clone

在Object中提供了一个方法clone,它的定义如下

Protected Object clone() throws CloneNotSupportedException

创建并返回此对象的一个副本,它在类中可以使用下面的语句

Super.clone();

例子如下:

在类中使用clone方法时,该类需要实现Cloneable接口,并且把clone的方法定义为public。

深入研究clone方法

String虽然是作为对象出现的,但是由于String的不可变性,所以在克隆中String不会产生这样的问题。

package ch07;

class Addr implements Cloneable{

String

country;

String

province;

String

city;

public Addr(String country, String province, String city)

{

super();

this.country = country;

this.province = province;

this.city = city;

}

public Object clone(){

Addr addr=null;

try{

addr=(Addr) super.clone();

}catch(CloneNotSupportedException e){

e.printStackTrace();

}

return addr;

}

}

class Human1 implements

Cloneable{

String

name;

String

sex;

Addr

addr;

public Human1(String name, String sex, Addr addr) {

super();

this.name = name;

this.sex = sex;

this.addr = addr;

}

public Object clone(){

Human1 h=null;

try{

h=(Human1) super.clone();

h.addr=(Addr) this.addr.clone();//此处重要

}catch(CloneNotSupportedException e){

e.printStackTrace();

}

return h;

}

}

public class TestClone {

public static void main(String[] args) {

// TODO Auto-generated method stub

Addr addr=new Addr("中国","北京","朝阳区");

Human1 zhangsan=new Human1("张三","男",addr);

Human1 lisi=(Human1) zhangsan.clone();

System.out.println("张三的地址:");

System.out.println(zhangsan.addr.country+"."+zhangsan.addr.province+"."+zhangsan.addr.city);

System.out.println("李四的地址:");

System.out.println(lisi.addr.country+"."+lisi.addr.province+"."+lisi.addr.city);

lisi.addr.country="中国";

lisi.addr.province="陕西省";

lisi.addr.city="西安";

System.out.println("修改李四的地址:");

System.out.println("张三的地址:");

System.out.println(zhangsan.addr.country+"."+zhangsan.addr.province+"."+zhangsan.addr.city);

System.out.println("李四的地址:");

System.out.println(lisi.addr.country+"."+lisi.addr.province+"."+lisi.addr.city);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值