This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I am not able to get the difference between the methods we define in private void writeObject(ObjectOutputStream) . ie:
defaultWriteObject() & writeObject(object) .
According to me :
-- If we are using a transient instance & we want save its state aswell, for this case we use defaultWriteObject(). It allows the normal serialization to take place from the main method of the other class.
If you implement theand in your Serializable class, then these methods will be invoked instead of the default writeObject() and the default readObject() methods during serialization and deserialization .
Generally we implement these methods in a class, if for the objects of some class we want to specify serialization and deserialization behaviour that is different than the default behaviour. Like for example one of the case might be that we want to preserve the state of transient variables. So you would implement those two private methods to ensure that whenever you serialized or deserialized an object of this class, your custom serialization and deserialization rules would apply instead of the default rules.
Generally people use these methods to specify additional fields ( the ones that would not be serialized during the default serialization - example transient fields ) that they'd want to also serialize during serialization and deserialize during deserialization. So if you want behaviour that adds to the default behaviour, you must have some means to ensure that those fields which would be serialized by the default serialization are also covered in your custom rules. o.defaultWriteObject() and i.defaultReadObject() methods do that job.
For this, we invoke the o.defaultWriteObject() in the private void writeObject(ObjectOutputStream o ) method and i.defaultReadObject() in private void readObject(ObjectInputStream i ) methods. The o.defaultWriteObject() and i.defaultReadObject() methods take care of converting object stream to byte stream and vice versa as per the default serialization and deserialization rules. After these methods, we write our custom serialization rules like o.writeInt(<some static/transient variable >) etc in the private void writeObject(ObjectOutputStream o ) method and our custom deserialization rules like i.readInt() etc in the private void readObject(ObjectInputStream i ) method.
We can serialize fields ( the ones covered by default rules and the ones covered by custom rules ) in any order but it is important we deserialize them in the same order.