Serialization

A Java Class Object needs to serialized if we need to store or transfer with the state values.

For any IO operations or network operations usually the java class objects needs to sent/received via network via bytes.

During serialization, Object along with state is serialized to bytes and can be processed between the systems as streams.

Below is the simple example for storing the Object with its state into a file., and reading back from the file with its state without losing it.
The Object to be stored, must be serialized.

Class Libraries in Java check each object whether it implements Serializable interface, and if so then the object will be Serializable.
Java class libraries will check all objects implemented the interface , and make them fit for serialization.

ObjectInputStream
Reading an Object which is stored in File or any Stream

ObjectOutputStream
Writing a Object into a File or Stream

Since Serializable is an empty interface, it is a Marker Interface.

Simple Object “Car”, we are going to store/read from file, with the state(values).

Note we have implemented Serializable in Car Class…….

If we are not implementing Serializable Interface, then the values are all stored as null for the fields like carName, numberOfWheels, fuelType etc.,

Result:

Leave a Reply

Your email address will not be published. Required fields are marked *