Prerequisites of Serialization
Implementing the Serializable Interface: A class to be serialized must implement the java.io.Serializable
interface. This interface is a marker interface, meaning it does not contain any methods but serves to indicate that a class can be serialized.
import java.io.Serializable;
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
serialVersionUID: The serialVersionUID
is a unique identifier for each class that implements the Serializable
interface in Java. This identifier is used during the deserialization process to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID
than that of the corresponding sender’s class, deserialization will result in an InvalidClassException
. It ensures version compatibility between sender and receiver during serialization and deserialization.
It is declared as a static final long field within the class. private static final long serialVersionUID = 1L;
Inheritance in Serialization
- Serializable Superclass: If the superclass implements
Serializable
, it will be serialized along with the subclass. If the superclass is Serializable, then by default, every subclass is serializable. Hence, even though subclass doesn’t implement Serializable interface( and if its superclass implements Serializable), then we can serialize subclass object. - Non-Serializable Superclass: If the superclass does not implement
Serializable
, the serialization process will handle the fields of the superclass differently. The default constructor of the superclass will be called during deserialization. (So every non-serializable superclass must necessarily contain a default constructor. Otherwise, we will get a runtime exception). JVM ignores the original value of that instance variable and saves the default value to the file.
Composition in Serialization
Composition refers to having objects of other classes as fields in a class. When a class contains other objects, these objects must also be serializable for the containing class to be serializable. If not, either declare that reference as transient or we will get an exception while calling serialize method.