Posted on 2008-08-02 07:16
夢與橋 閱讀(180)
評論(0) 編輯 收藏 所屬分類:
java基礎
1、目的:為了獲得對象的一份拷貝。
2、一般步驟:§在派生類中覆蓋基類(object)的clone方法,并聲明為public
§在派生類的克隆方法中調用super.clone()
§在派生類中實現Cloneable接口
3、分類:淺拷貝、深拷貝
§淺拷貝僅僅拷貝所考慮的對象,而不拷貝它所引用的對象
§深拷貝把要拷貝的對象所引用的對象都拷貝了一遍
4、淺拷貝實例:
class Book implements Cloneable
{
private String name;
private double price;
public Author author;
Book(String name,double price,Author author)
{
this.name=name;
this.price=price;
this.author=author;
}
public String toString()
{
return "book's name:"+name+"\t\tbook's price:"+price+author.tostring();
}
public Object clone()
{
Object o=null;
try
{
o=super.clone();
}
catch (CloneNotSupportedException e)
{
System.out.println(e.toString());
}
return o;
}
}
class Author
{
private String name;
private int age;
Author(String name,int age)
{
this.name=name;
this.age=age;
}
public void set(String name,int age)
{
this.name=name;
this.age=age;
}
public String tostring()
{
return "\nauthor's name:"+name+"\t\tauthor's age"+age;
}
}
public class Test
{
public static void main(String args[])
{
Author author=new Author("孫悟空",800);
Book book1=new Book("高等數學",32.00,author);
Book book2=(Book)book1.clone();
book1.author.set("唐僧",700);//此處的修改影響到了book2,體現了淺拷貝的特點
System.out.println(book2);
}
}
5、深拷貝實例:
class Book implements Cloneable
{
private String name;
private double price;
public Author author;
Book(String name,double price,Author author)
{
this.name=name;
this.price=price;
this.author=author;
}
public String toString()
{
return "book's name:"+name+"\t\tbook's price:"+price+author.tostring();
}
public Object clone()
{
Book o=null;
try
{
o=(Book)super.clone();
}
catch (CloneNotSupportedException e)
{
System.out.println(e.toString());
}
o.author=(Author)author.clone();
return o;
}
}
class Author implements Cloneable
{
private String name;
private int age;
Author(String name,int age)
{
this.name=name;
this.age=age;
}
public void set(String name,int age)
{
this.name=name;
this.age=age;
}
public String tostring()
{
return "\nauthor's name:"+name+"\t\tauthor's age"+age;
}
public Object clone()
{
Object o=null;
try
{
o=super.clone();
}
catch (CloneNotSupportedException e)
{
System.out.println(e.toString());
}
return o;
}
}
public class Test
{
public static void main(String args[])
{
Author author=new Author("孫悟空",800);
Book book1=new Book("高等數學",32.00,author);
Book book2=(Book)book1.clone();
book1.author.set("唐僧",700);//此處的修改沒有影響book2,體現了深拷貝的特點。
System.out.println(book2);
}
}
6、注意:
§在派生類中覆蓋Object的clone()方法時,一定要調用super.clone(),因為在運行時刻,Object中的clone()識別出你要復制的是哪一個對象,然后為此對象分配空間,并進行對象的復制,將原始對象的內容一一復制到新對象的存儲空間中。
§在Object.clone()正式開始操作前,首先會檢查一個類是否Cloneable,即是否具有克隆能力——換言之,它是否實現了Cloneable接口。若未實現,Object.clone()就擲出一個CloneNotSupportedException違例,指出我們不能克隆它。