public class test5 {
public static void main(String[] args) throws CloneNotSupportedException {
Boss b1=new Boss("张三");
Boss b3=(Boss) b1.clone();
System.out.println(b1==b3);
System.out.println(b1.equals(b3));
}
}
class Boss implements Cloneable{
private String name;
public Boss(String name) {
this.name=name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
return super.equals(obj);
}
}
================
false
false
============
克隆:实现Cloneable接口,并重写clone()方法。
所谓浅克隆,就是将要克隆的对象的属性方法进行克隆,它的内容一样,但是所指向的内存是不一样的,它并没有克隆对象中的引用类型属性。
深克隆就是要将要克隆的对象的引用类型变量同样进行克隆。例:
package test;
public class test5 {
public static void main(String[] args) throws CloneNotSupportedException {
Boss b1=new Boss("张三");
/*Boss b3=(Boss) b1.clone();
System.out.println(b1==b3);
System.out.println(b1.equals(b3));*/
Run r=new Run("跑跑");
b1.setRun(r);
Boss b2=(Boss) b1.clone();
System.out.println(b1.getRun()==b2.getRun());
}
}
class Run implements Cloneable{
private String run;
public Run(String run) {
super();
this.run = run;
}
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
}
class Boss implements Cloneable{
private String name;
private Run run ;
public Run getRun() {
return run;
}
public void setRun(Run run) {
this.run = run;
}
public Boss(String name) {
this.name=name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
protected Object clone() throws CloneNotSupportedException {
// 本身是调用Object类的方法,只把Boss类的对象进行克隆
//现在是将Boss的引用属性也进行克隆
Boss b=(Boss) super.clone();
b.run=(Run) run.clone();
return b;
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
return super.equals(obj);
}
}
==========
false
=======
这样将克隆对象的引用属性也克隆叫深克隆