16.07. Serialization of Objects

Serialization of Objects

  • Eclipse: Oxygen
  • Java: 1.8

Serialization of Objects

It is the converting of Java objects into byte streams and deserialization, as the name suggests, in a contrast to it. Stated differently, serialization is the conversion of a Java object into a static stream (sequence) of bytes which can then be saved to a database or transferred over a network.

Here we are casting the information using another kind of vehicle version id class. Whereas we are reading some other vehicle id class. When we are trying to cast the information there is some inconsistency, issues with the version id. Making use of serialization is it gives us an additional layer of consistency, so there is no inconsistency throughout the application and we are making use of the exact class for casting the information while reading the file.

Java code for serialization

In the following program, to serialize an object, we need to ensure that the class of the object implements the java.io.Serializable interface. Serializable is a marker interface; It does not declare any method and tells the serialization mechanism that the class can be serialized.

Now that we have made the class eligible for serialization, the next step is really to serialize the object. This is done by calling the writeObject() method of the java.io.ObjectOutputStream class.

Object restoration occurs with the call to the obj.readObject() method. readObject() method can read any serializable object, a conversion to the correct type is required.

Contributed by: Poonam Tomar

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments