Well, all these questions are going to be answered with a code example, but before that, let's get a feel for serialization.

In plain English, serialization is a process 'to arrange in a series and broadcast it to the outer world'. So in Java, we send a serializing object to the network stream and publish or send it to a directory to store its form for the future use.

Let's jump on an example to learn more. And if you want to know even more, be sure to check out the 'points to be noted' section.

Points to be Noted in Employee.java:

serialVersionUID is explicitly defined to prevent InvalidClassException during deserialization, as the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations and can produce different serialVersionUIDs in different environments.

firstName will be serialized, and the default value can be overridden in subsequent classes that are serializing Employee.java

middleName, lastName and nickName are either transient static or transient final. Always remember, transient and static fields are never get serialized. The value which will be restored for these variables will be the value mentioned in the Employee.class at the time of deserialization.

explicitAge is private. It will be serialized as well but can be read only through Reflection API.

PersonalDetails is a class that is implementing a serializable interface. If it won't, then NullPointerException will be thrown at the time of serialization. Its field's value can be overridden in the subsequent classes. Note that the 'age' field is transient.

There is an interface available to validate the object and its data called 'ObjectInputValidation'. And to validate, the validateObject() method needs to be overridden.

Please note that the parent class 'Manager' is not implementing the Serializable interface. Though it won't throw any exception, as we are not composing or aggregating the parent class object inside the child class Employee.java. So here, the only point we can observe is that the transient keyword won't work here.

'Company' is an interface, so all its fields are final by default. Please note Interface does not accept the transient keyword for its member variables.

Output

Still thinking about the security of your object? If you want to encrypt and sign the entire object, then go for either the javax.crypto.SealedObject and/or java.security.SignedObject wrappers. Both are serializable and box the original object.

But what happens to the Singleton class when it gets serialized? Oops, it creates the new object! Don't worry! Implement the following method, which can be used to unpack the proxy.