有人說這樣的是淺克?。篶lass Book implements Cloneable{ private String name; private double price; public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public Book(String name,double price){ this.name=name; this.price=price; } @Override public String toString(){ return name+":"+price; } @Override public Object clone() throws CloneNotSupportedException{ return super.clone(); }}class Student{ private String name; private Book book;}public class CloneTest { public static void main(String[] args) throws CloneNotSupportedException { Book b1 = new Book("luoweideshenlin",26); Book b2 = (Book)b1.clone();//不等價(jià):b2=b1; b2.setName("pingfandeshijie"); b2.setPrice(78); System.out.println(b1.toString()); System.out.println(b2.toString()); System.out.println(b1==b2); }}這個(gè)的輸入結(jié)果是:luoweideshenlin:26.0pingfandeshijie:78.0false那怎么樣算深克隆呢,
1 回答

cxxyjsj
TA貢獻(xiàn)119條經(jīng)驗(yàn) 獲得超22個(gè)贊
深復(fù)制不僅復(fù)制對(duì)象本身,也會(huì)復(fù)制對(duì)象的成員變量. 你可以試下Student類默認(rèn)的克隆方法, 克隆后兩個(gè)Studnet對(duì)象引用的book對(duì)象實(shí)際上是同一個(gè).
添加回答
舉報(bào)
0/150
提交
取消