Static variables cannot be serialized, as serialization is meant for only objects and not for class.
Now my doubt is, if we use the static variables in the class, and while serializing the object , the value of static variable may be different and when deserializing the object the static variable may be different.
How it will restore the correct value for the object which is deserialized?
Do we have to serialise it manually ?How it will work?
Ulf Dittmer
Marshal
Joined: Mar 22, 2005
Posts: 35247
7
posted
0
There is no single "correct" value for static fields. Serialization simply ignores them. So if an object is deserialized, the static fields of that class remain what they were before the deserialization. If you want fields that can change on a per-object basis, they can't be static.
That's true. As Ulf said, the static values never come into picture of the serialization at all. They are treated as if the "instance variables marked as transient"!
Do we have to serialise it manually ?How it will work?
If you really want to serialize/deserialize static variables, then you can implement the readObject() and writeObject() methods for the class. (technically, it is not "override" since these are private methods).
However, keep in mind, that when you deserialize, you will be changing a static variable -- which is a variable used by every object of that class type.