To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable if this is not the case. The error will be detected at runtime. JAVA API
But I have a question. When I removed the comments (see modified code below) and compiled and executed it, it gives me InvalidClassException when the out.writeObject() line is executed. So I decided that it is using the defaultWriteObject() of the ObjectOutputStream class so I created my own implementation of writeObject() but still it gives me InvalidClassException. What is the reason behind this?
Exception in thread "main" java.io.InvalidClassException: B; B; no valid constructor
at java.io.ObjectStreamClass.checkDeserialize(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
Caused by: java.io.InvalidClassException: B; no valid constructor
at java.io.ObjectStreamClass.<init>(Unknown Source)
at java.io.ObjectStreamClass.lookup(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
that references to "out.writeObject(b);".
Ankit Garg wrote:If you would have tried, then you must have noted that there is no exception while serialization. The exception occurs during deserialization as A is not serializable so the JVM tries to call a no-arg constructor for A which is not found resulting in an exception...
Banu Chowdary wrote:I got the point.....................
while deserialization the object , if the super class is not serializble then it's no-arg constructor will be called and if it is not there then we will get Exception. Am I Right ??