Here is a very simple 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 do not understand why his conclusion:
Result: 5 & -1 Result: 5 & -1
Since static members are not serialized and therefore get default values, I expected a different output:
Result: 5 & -1 Result: 0 & -1
How did the deserialized object get the correct static field value?
I made this test application because I need to serialize several objects with several static fields to make deep copies (and, of course, I need to be sure that the copies have the same values โโof static fields, since they are used as array indices).
And now I'm completely confused about what happens after deserialization. On the one hand, static members are not serialized, but, on the other hand, as the example shows, static members somehow retain their values. I suspect this has something to readObject() to a Body object, but I'm not sure.
source share