static in serialization
i have a doubt in serialization. i have read that static variables are not serialized.
but when i tested it does...?
public static void main(String ... args)
Model obj = new Model();
obj.a += 10;
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("myfile"));
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("myfile"));
obj = (Model)ois.readObject();
System.out.println("a = "+obj.a);
System.out.println("b = "+obj.b);
class Model implements Serializable
static int a = 7;
transient int b = 11;
whats happening here?
does static variables saved on serialization?
thanks in advance....
When you instantiate a new Model, the class is loaded and initialized; you set the static member variable to 17. When an object is deserialized its class is loaded and initialized unless it already is; here the class Model is already loaded and initialized so a ends up to be equal to 17. Transient members aren't saved to the stream as you could have noticed.