SERIALIZATION

What is Serialization

Serialization is a process in which current state of Object will be saved in stream of bytes. As byte stream create is platform neutral hence once objects created in one system can be deserialized in other platform.

What is the use of Serialization

As written above serialization will translate the Object state to Byte Streams. This Byte stream can be used for different purpose.
  • Write to Disk
  • Store in Memory
  • Sent byte stream to other platform over network
  • Save byte stream in DB(As BLOB)

Serialization and Deserialization in Java

Now we know what is serialization. But in terms of Java how this serialization will work and how to make a class serializable. Java has already provided out of the box way(java.io.Serializable  Interface) to serialize an Object. If you want any class to be serialized then that class needs to implement give interface.
Note*: Serializable Interface is a Marker Interface. Hence there is no method in Serializable interface.
 serialization and deserialization of objects

Code for Serialization of Java Class

Employee.java

SerializaitonClass.java

DeserializationClass.java
First run “SerializaitonClass” and you will get “employee.txt” file created.
Second run “DeserializationClass” and java will deserialize the class and value will be printed in console.
Output would be

Bullet Points

  • Serialization interface needs to be implemented in order to make object serialized.
  • Transient instance variable doesn’t serialized with Object state.
  • If Super class implements Serializable then sub class are also Serializable automatically.
  • If Super class is not serializable then when sub class is de serialized then super class’s default constructor will be invoked. Hence all variable will get default value and reference will be null.

No comments:

Post a Comment