为了账号安全,请及时绑定邮箱和手机立即绑定

java里的深克隆与浅克隆问题,百度看着傻傻分不清

java里的深克隆与浅克隆问题,百度看着傻傻分不清

冯宝宝 2017-11-26 22:13:32
有人说这样的是浅克隆:class 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();//不等价:b2=b1; b2.setName("pingfandeshijie"); b2.setPrice(78); System.out.println(b1.toString()); System.out.println(b2.toString()); System.out.println(b1==b2); }}这个的输入结果是:luoweideshenlin:26.0pingfandeshijie:78.0false那怎么样算深克隆呢,
查看完整描述

1 回答

?
cxxyjsj

TA贡献119条经验 获得超22个赞

深复制不仅复制对象本身,也会复制对象的成员变量. 你可以试下Student类默认的克隆方法, 克隆后两个Studnet对象引用的book对象实际上是同一个.

查看完整回答
反对 回复 2017-11-27
  • 1 回答
  • 0 关注
  • 1182 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信