Why it's needed to write defaultReadObject() and defaultWriteObject() as the first statement in readObject(ObjectInputStream o) and writeObject(ObjectOutputStream o) methods when a class implements serializable interface.
defaultReadObject() and defaultWriteObject() should be the first method call inside readObject(ObjectInputStream o) and writeObject(ObjectOutputStream o). It reads and writes all the non transient fields of the class respectively. These methods also helps in backward and future compatibility. If in future you add some non-transient field to the class and you are trying to deserialize it by the older version of class then the defaultReadObject() method will neglect the newly added field, similarly if you deserialize the old serialized object by the new version then the new non transient field will take default value from JVM i.e. if its object then null else if primitive then boolean to false, int to 0 etc….
Here some useful lines from the Docs
defaultReadObject() method read the non-static and non-transient fields of the current class from this stream.
And as same for the writing too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With