Here's a very basic test program:
public class Body implements Serializable {
static int bod = 5;
int dis = -1;
public void show(){
System.out.println("Result: " + bod + " & " + dis);
}
}
public class Testing {
public static void main(String[] args) {
Body theBody = new Body();
theBody.show();
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("test.dat"));
out.writeObject(theBody);
out.close();
ObjectInputStream in = new ObjectInputStream(new FileInputStream("test.dat"));
Body bodyDouble = (Body)in.readObject();
in.close();
bodyDouble.show();
} catch(IOException e) {
} catch(ClassNotFoundException e) {
}
}
}
But I don't understand why its output is:
Result: 5 & -1
Result: 5 & -1
Since static members are not serialized and hence get default values I was expecting another output:
Result: 5 & -1
Result: 0 & -1
How did the deserialized object acquire the right static field value?
I've made this test application because I need to serialize a few objects with a number of static fields in order to make deep copies (and of course, I need to be sure that copies have the same static fields' values since they are used as array indices).
And now I'm absolutely confused about what happens after deserialization. On the one hand, static members don't get serialized but, on the other hand, as the example prooves, static members somehow preserve their values. I suspect that it has something to do with casting of readObject()
to the Body
object but I'm not sure.