Before coming to the topic let us discuss some basics of serialization.
What is ‘Serialization’?
Serialization is a procees of saving the state of an object by converting it into a stream of bytes. This stream of bytes can be sent over a network, stored in a file or simply can be used to manipulate data. The advantage it has over non-searialized object is that data is not lost while transfering.
What does java.io.Serializable do?
If a class implements java.io.Serializable interface, it doess not mean that its instance is serialized. It means it is just marked for serialization, just to tell the compiler that its instance can be serialized. We have methods to serialize objects. For e.g ObjectOutputStream(OutputStream out).
Now coming back to the original discussion, what is the need for a no-argument constructor while serialization, let us understand the process in which serialization takes place. Serialization works by chaining up each class in the inheritance heirarchy and then saving the state of each superclass untill the first non-serialization class is reached.
Now, when we try to deserialze the object, the state of the non-serializable super class(which is required to construct the exact state of the object) can not be restored from the stream, and is instead restored by invoking the no-arg constructor.
The problem arises when the no-arg constructor of the first non-serializable class is not accessible, throwing an exception ‘InvalidClassException: no valid constructor’
As we know by default each java class has a no-arg constructor. So, how can it be inaccessible some times?
The answer is: The default no-arg constructor is invoked only if no other constructor with arguments is declared in the class. In this case, in order to invoke thr no-arg constructor we need to declare it separately.