一、clone的用法:
package chatRoom.F5;
class Person implements Cloneable{//1.
public String name;
public Person(String name) {
this.name = name;
}
//2.
protected Person clone() throws CloneNotSupportedException {
return (Person)super.clone();//重写Object类的clone
}
}
//clone(): 复制对象。
public class CloneDemo {
public static void main(String[] args) throws CloneNotSupportedException {
Person p1=new Person("zs");
Person p2=p1.clone();//p2表示复制出来的第二份儿对象
}
}
二、clone的浅克隆:
如果具有引用类型成员变量的类,单纯的重写了clone方法。 则调用clone方法进行对象克隆时就是浅克隆(只是克隆了此类对象,内部的引用类型属性指向的对象没有被克隆)。
package chatRoom.F5;
class Person implements Cloneable{//1.
public String name;
public Person(String name) {
this.name = name;
}
//2.
protected Person clone() throws CloneNotSupportedException {
return (Person)super.clone();//重写Object类的clone
}
}
class ClassRoom implements Cloneable{
int id;
Person p1;
protected ClassRoom clone() throws CloneNotSupportedException {
return (ClassRoom)super.clone();//浅克隆
}
}
public class CloneDemo {
public static void main(String[] args) throws CloneNotSupportedException {
ClassRoom c=new ClassRoom();//第一个ClassRoom
c.p1=new Person("赵公明");
//ClassRoom复制时,没有复制ClassRoom里边的Person对象
ClassRoom d=c.clone();//第2个ClassRoom
System.out.println(c.p1 == d.p1);
}
}
三、clone的深克隆:
如果具有引用类型成员变量的类,此时若需要进行深克隆,则需要重写了clone方法,并在clone方法中调用引用类型成员变量的clone方法对引用类型变量指向的对象都进行克隆。
package chatRoom.F5;
class Person implements Cloneable{//1.
public String name;
public Person(String name) {
this.name = name;
}
//2.
protected Person clone() throws CloneNotSupportedException {
return (Person)super.clone();//重写Object类的clone
}
}
class ClassRoom implements Cloneable{
int id;
Person p1;
protected ClassRoom clone() throws CloneNotSupportedException {
//改进:实现深克隆
//方式:p1也调用clone
ClassRoom c=(ClassRoom)super.clone();
c.p1=p1.clone();
return c;//浅克隆
//return (ClassRoom)super.clone();
}
}
public class CloneDemo {
public static void main(String[] args) throws CloneNotSupportedException {
ClassRoom c=new ClassRoom();//第一个ClassRoom
c.p1=new Person("赵公明");
//ClassRoom复制时,没有复制ClassRoom里边的Person对象
ClassRoom d=c.clone();//第2个ClassRoom
//c中的p1对象的地址==d中的p1对象的地址
System.out.println(c.p1 == d.p1);//false
}
}