Wednesday, 17 February 2016

Object serialization and deserilaization. Saving file to desk. File input output.

Object Serialization and Deserialization


 Serialization helps save the state of the objects. To be serialized the class of that object must implement the Serializable interface. If a class implements the interface Serialization then objects of  all of its subclasses are serializable. When an object is serialized, its entire object graph is serialized, i.e., if the object has references to other objects then they are also serialized. 

If you don't want to serialize some of the instance variables then make them "transient". Then that variable will be skipped during the process of serialization and during the deserialization that object will get null as value if it is a reference object or default value if it is of type primitive. 

Deserialized objects are read in the same order in which they were serialized. Since the type of the object that is deserialized is of class Object therefore it must be casted to their real type.  

Static variables are not deserialized as all instances of a class share a static variable. A static variable is per class and not per instance. So it doesn't make sense to save a static variable value as part of a specific objects state since all objects of that type share only a single value - the one in the class.


Example program:


 In this program we write a class that makes game characters. We make three instances/objects and save them to desk after serialization. Then we set those three references to null so that we can not access them on the heap. Next, we have code for deserializatin of those characters to inflate them again and give them life on the heap. We print the values of the instance variables of these three objects both before serialization and after deserialization to show that it works.

To see the code please click

here

No comments:

Post a Comment