我参考了B类中的A类,两者都是可序列化的。我在B类的两个不同对象中传递A的相同参考,如下所示:
class A implements Serializable {
private Integer a;
A(Integer a) {
System.out.println("Constructor with argument Called");
this.a = a;
}
A() {
System.out.println("Constructor Called");
}
public Integer getA() {
return a;
}
public void setA(Integer a) {
this.a = a;
}
}
class B implements Serializable {
A a = null;
public A getA() {
return a;
}
public void setA(A a) {
this.a = a;
}
}
public class SerializeDemo {
public static void main(String[] args) throws Exception {
A a1 = new A(10);
B b1 = new B();
B b2 = new B();
b1.setA(a1);
b2.setA(a1);
FileOutputStream fos = new FileOutputStream("abc.ser");
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(b1);
b2.getA().setA(20); // here i have set the value to 20 but in output its coming 10 only
os.writeObject(b2);
os.close();
System.out.println("Serialization Done");
FileInputStream fis = new FileInputStream("abc.ser");
ObjectInputStream os1 = new ObjectInputStream(fis);
B b3 = (B) os1.readObject();
B b4 = (B) os1.readObject();
fis.close();
System.out.println(b3.toString());
System.out.println(b4.toString());
System.out.println(b3.getA());
System.out.println(b4.getA());
System.out.println(b3.getA().getA());
System.out.println(b4.getA().getA());
}
}
输出如下:
Constructor with argument Called
Serialization Done
org.jnbis.B@18f55759
org.jnbis.B@1339a0dc
org.jnbis.A@6096b38e
org.jnbis.A@6096b38e
10
10
由于A也是可序列化的,所以我期待b4的输出为20,但它的即将到来。为什么?