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