对象克隆
class Money1 { double money = 10.0; } class Person1 implements Cloneable{ public String name; Money1 m; public Person1(String name){ this.name = name; m = new Money1(); } } public class TestCloneDemo1 { public static void main(String[] args) throws Exception { /*student s1 = new student(10); System.out.println(s1);*/ Person1 p1 = new Person1("caocao"); Person1 p2 = (Person1)p1.clone();//这里会报错 此时要对clone方法进行重写
class Money1 { double money = 10.0; } class Person1 { public String name; Money1 m; public Person1(String name){ this.name = name; m = new Money1(); } protected Object clone() throws CloneNotSupportedException { //Person重写 Person1 p = (Person1)super.clone(); return p; } }
重写后仍然会报错 这是Person1类没有实现Cloneable这个接口
作用:
class Money1 { double money = 10.0; } class Person1 implements Cloneable{ public String name; Money1 m; public Person1(String name){ this.name = name; m = new Money1(); } protected Object clone() throws CloneNotSupportedException { //Person重写 Person1 p = (Person1)super.clone();//强转 clone()方法是基类object里面的方法 return p; } }
public static void main(String[] args) throws Exception { /*student s1 = new student(10); System.out.println(s1);*/ Person1 p1 = new Person1("caocao"); Person1 p2 = (Person1)p1.clone(); System.out.println(p1.m.money); System.out.println(p2.m.money); p1.m.money = 1000.0; System.out.println(p1.m.money); System.out.println(p2.m.money);
结果
10.0 10.0 1000.0 1000.0
改变p2的值p1的值也变了,???
只克隆了person对象,并没有克隆Money对象。需要在money类写入clone()方法
class Money1 implements Cloneable{ double money = 10.0; @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } } class Person1 implements Cloneable{ public String name; Money1 m; public Person1(String name){ this.name = name; m = new Money1(); } @Override protected Object clone() throws CloneNotSupportedException { //Person重写 Person1 p = (Person1)super.clone(); p.m = (Money1)this.m.clone();//对当前对象内的引用进行克隆 return p; } } public class TestCloneDemo1 { public static void main(String[] args) throws Exception { /*student s1 = new student(10); System.out.println(s1);*/ Person1 p1 = new Person1("caocao"); Person1 p2 = (Person1)p1.clone(); System.out.println(p1.m.money); System.out.println(p2.m.money); p1.m.money = 1000.0; System.out.println(p1.m.money); System.out.println(p2.m.money); } }
结果:
10.0
10.0
1000.0
10.0
浙公网安备 33010602011771号