在内存中新创建(生成一个对象),并且对象中成员变量的属性也完全相同,在内存中存在两个对象。
想在原有对象的基础上产生新的数据,并且还想将原有的数据进行保存。
在克隆时对成员变量进行简单的赋值操作,两个对象的成员变量进行一一赋值,如果成员变量为基本数据类型,那将不会产生影响(基本数据类型的赋值会创建新的地址)而引用数据类型则不会,只是简单地将对象的地址值进行赋值,这样两个引用指向同一个地址,当一个引用类型的成员变量改变后就会影响另一个对象的成员变量也发生改变,并不能将原有的数据进行保存。
public class Person implements Cloneable {
String name;
int age;
Person girlFriend;
public Person(int age, String name) {
this.age = age;
this.name = name;
}
public void setFri(Person person) {
this.girlFriend = person;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", girlFriend=" + girlFriend +
'}';
}
@Override
public Person clone() {
Person p = null;
try {
p = (Person) super.clone();
if (p.girlFriend != null) {
p.girlFriend = p.girlFriend.clone();// girlFriend为引用类型的成员变量,需要再次进行浅克隆,注意:克隆的引用类型成员变量也需要实现Cloneable接口
}
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return p;
}
}
import java.io.*;
public class Person implements Serializable {
String name;
int age;
Person girlFriend;
public Person(int age, String name) {
this.age = age;
this.name = name;
}
public void setGirlFriend(Person person) {
this.girlFriend = person;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", girlFriend=" + girlFriend +
'}';
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
Person oldPerson = new Person(18, "zhangsan");
oldPerson.setGirlFriend(new Person(21, "honghong"));
Person newPerson = null;
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("E:\\test.txt"));
output.writeObject(oldPerson);
ObjectInputStream input = new ObjectInputStream(new FileInputStream("E:\\test.txt"));
newPerson = (Person) input.readObject();
newPerson.girlFriend.age = 25;
newPerson.girlFriend.name = "lili";
System.out.println(oldPerson);
System.out.println(newPerson);
}
}