Java serialization is automatic by implementing Serializable interface. The implementation is present in the ObjectInputStream and ObjectOutputStream classes.
But what if we want to change the default Serialization (we have some sensitive information in the object and before saving/retrieving we want to encrypt/decrypt it.
There are four methods that we can provide in the class to change the serialization behavior.
1.readObject(ObjectInputStream ois): If this method is present in the class, ObjectInputStream readObject() method will use this method for reading the object from stream.
2.writeObject(ObjectOutputStream oos): If this method is present in the class, ObjectOutputStream writeObject() method will use this method for writing the object to stream.
3.Object writeReplace(): If this method is present, then after serialization process this method is called and the object returned is serialized to the stream.
4.Object readResolve(): 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.