Java serialization is an automatic process which uses to save the object state and restore it when it required. To save and read the object state took place by using methods defaultWriteObject, defaultReadObject respectively.
In the default mechanism, static field and transient variable are not serialized or deserialized. As an example, if we want to serialize transient variable we need to use readObject and writeObject. Sometimes, we want to change the default Serialization to save the sensitive information in the object and before saving/retrieving we want to encrypt/decrypt it. We can modify the default serialization process readObject and writeObject methods.
There are four methods that we can provide in the class to change the serialization behavior.
If this method is present in the class, ObjectInputStream readObject() method will use this method for reading the object from stream.
If this method is present in the class, ObjectOutputStream writeObject() method will use this method for writing the object to stream.
If this method is present, then after serialization process this method is called and the object returned is serialized to the stream.
If this method is present, then after deserialization process, this method is called to return the final object to the caller program. This method is used to implement Singleton pattern with Serialized classes.
All four methods are kept as private so that subclasses can’t override them. They are meant for serialization purpose only and keeping them private avoids any security issue.