Hi All,
K&B (SCJP1.5) page 456 says that serialization is not for statics. I understand that statics are class variables hence do not get saved during serialization. So that led me to try and find out what happens when an object which has a static member is saved. What happens when the object is saved then read back?
I tried to solve the above with the folowing code:
====================================================
import java.io.*;
public class TestStatic implements Serializable{
public static int x = 0;
public TestStatic(){
x = 1;
}
public static void setTestStatic(){
x = 2;
}
public static void main(
String[] args) throws Throwable{
TestStatic W = new TestStatic();//x is 1
W.setTestStatic(); // x is 2
File f = new File("a.txt");
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f));
oos.writeObject(W);
oos.close();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
TestStatic A = (TestStatic)ois.readObject();
System.out.println(A.x);
ois.close();
}
}
====================================================
This gives the output "2" which is what the static variable was just before it was saved. I thought maybe staic variables get thier initial values like transient variables but this is not the case.
Thanks
Can anyone explain what happens to static variables when they are saved and then read back?
Thanks