java笔记之对象的克隆

时间:2022-05-09 19:36:48

对象的克隆
对象的浅克隆:
    对象浅克隆要注意的细节:
    1. 如果一个对象需要调用clone的方法克隆,那么该对象所属的类必须要实现Cloneable接口。
    2. Cloneable接口只不过是一个标识接口而已,没有任何方法。
    3. 对象的浅克隆就是克隆一个对象的时候,如果被克隆的对象中维护了另外一个类的对象,这时候只是克隆另外一个对象的地址,而没有把
     另外一个对象也克隆一份。

    4. 对象的浅克隆也不会调用到构造方法的。

class Address implements Cloneable{
String city;
public Address(String city) {
this.city=city;
}
}
class people implements Cloneable{
Address address;
String name ;
int id;
public people(int id,String name ,Address address) {
this.id=id;
this.name=name;
this.address=address;
}
@Override
public String toString() {
return "姓名:"+this.name+" 编号:"+this.id+" 地址:"+this.address.city;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Demo02 {
public static void main(String[] args) throws Exception {
Address address
=new Address("广州");
people p1
=new people(110,"狗娃",address);
people p2
=(people) p1.clone();
address.city
="长沙";
System.
out.println("p1:"+p1);
System.
out.println("p2:"+p2);
}
}

输出结果;

p1:姓名:狗娃 年龄:110 地址:长沙
p2:姓名:狗娃 年龄:110 地址:长沙 

对象的浅克隆就是克隆一个对象的时候,如果被克隆的对象中维护了另外一个类的对象,这时候只是克隆另外一个对象的地址,而没有把另一个对象克隆过去。

java笔记之对象的克隆

对象的深克隆: 对象的深克隆就是利用对象的输入输出流把对象先写到文件上,然后再读取对象的信息过程称作深克隆

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class Address implements Cloneable,Serializable{
String city;
public Address(String city) {
this.city=city;
}
}
class people implements Cloneable,Serializable{
Address address;
String name ;
int id;
public people(int id,String name ,Address address) {
this.id=id;
this.name=name;
this.address=address;
}
@Override
public String toString() {
return "姓名:"+this.name+" 编号:"+this.id+" 地址:"+this.address.city;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Demo02 {
public static void main(String[] args) throws Exception {
Address address
=new Address("广州");
people p1
=new people(110,"狗娃",address);
write(p1);
people p2
=read();
address.city
="长沙";
System.
out.println("p1:"+p1);
System.
out.println("p2:"+p2);
}
public static people read() throws Exception{
FileInputStream fileInputStream
=new FileInputStream("F:/obj.txt");
ObjectInputStream obj
=new ObjectInputStream(fileInputStream);

return (people) obj.readObject();

}
public static void write(people p) throws IOException{
FileOutputStream fileOutputStream
=new FileOutputStream("F:/obj.txt");
ObjectOutputStream
object=new ObjectOutputStream(fileOutputStream);
object.writeObject(p);
object.close();
}
}

输出结果:

p1:姓名:狗娃 编号:110 地址:长沙
p2:姓名:狗娃 编号:110 地址:广州