If a class has a reference to another class, all the references must be Serializable otherwise serialization process will not be performed. In such case, NotSerializableException is thrown at runtime.
Since Address is not Serializable, we are getting NotSerializableException while serializing the instance of Employee class.
How to fix the Serialization in the case of Association?
1. Using the transient keyword
In case the class refers to non-serializable objects and these objects should not be serialized, then, you can declare these objects as transient. Once a field of a class is declared as transient, then, it is ignored by the serializable runtime.
2. Using the static keyword
In serialization, static variables are not serialized, so during deserialization, static variable value will load the class.
3. Make it a Serializable object
All the objects within an object must be Serializable. To resolve the problem in the above example, we can implement the Serializable in Address class.
4. Modify the Serialization by implementing the readObject and writeObject methods
Phew! It is not working and throwing the same exception. writeObject and readObject methods have control only on the serialization of the class in which those are implemented.
5. Make it an Externalizable object
We can resolve this problem by using externalization which has complete command on the class.
After running the code, we can see that Address object is Serialized and Deserialized along with the Employee object. This is the best use case which helps us to understand the advantage of Externalizable over Serializable. Externalizable having an advantage when we want to serialize the third party API’ classes used in the association.