From the SCJP 6 study guide - there is a question asking for the output of the following code regarding serialization:
import java.io.*;
public class TestClass {
static public void main(String[] args) {
SpecialSerial s = new SpecialSerial();
try {
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("myFile"));
os.writeObject(s);
os.close();
System.out.print(++s.z + " ");
s = null; // makes no difference whether this is here or not
ObjectInputStream is = new ObjectInputStream(new FileInputStream("myFile"));
SpecialSerial s2 = (SpecialSerial)is.readObject();
is.close();
System.out.println(s2.y + " " + s2.z);
} catch (Exception e) {e.printStackTrace();}
}
}
class SpecialSerial implements Serializable {
transient int y = 7;
static int z = 9;
}
The output of this is: 10 0 10
The reason given for this is that the static variable z is not serialized, which I would not have expected it to be.
The value of the static int variable z is incremented to 10 after the object has been written to file, in the println() statement.
This being the case, why is it not back to either it's original value of 9 when the class is deserialized, or as the class is not being created in the normal way, the class default int value of 0, rather than remaining with it's non-default incremented value of 10 after deserialization? I would have thought the value of it being 10 would be lost, but this is not the case.
Anyone shed some light? I'm stumbling around here in the dark stubbing my toes on this one..
Basically, instances are serialized, not classes. Any static fields declared by the class are unaffected by serialization/deserialization of an instance of the class. For z
to be reset to 9
, the SpecialSerial
class would need to be reloaded, which is a different matter.
The value of s2.z
is the value of a static member z
of SpecialSerial
class, that's why it stays 10. z
is bounded by the class, and not the instance.
It's as if you've done this
++SpecialSerial.z
System.out.println(SpecialSerial.z)
instead of
++s.z
System.out.println(s2.z)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With