Question

When you save objects in Java using java.io.Serializable, if the object you're saving has objects of different classes within it, do those nested classes also have to implement serializable?

Was it helpful?

Solution

Generally, yes. If your class has non-transient member fields of reference types, and those fields are non-null at runtime, then the objects that those fields refer to must be Serializable in order for the referring object to be Serializable.

There are exceptions to this rule, generally by overriding the default serialization e.g. by implementing private methods that do the serialization by hand. See the comments in the header of the Serializable.java file:

 * Classes that require special handling during the serialization and
 * deserialization process must implement special methods with these exact
 * signatures: <p>
 *
 * <PRE>
 * private void writeObject(java.io.ObjectOutputStream out)
 *     throws IOException
 * private void readObject(java.io.ObjectInputStream in)
 *     throws IOException, ClassNotFoundException;
 * private void readObjectNoData()
 *     throws ObjectStreamException;
 * </PRE>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top