🚀 Enjoying Java Tutorials?
Subscribe to Ram N Java for clean, beginner-friendly core Java tutorials and interview prep!
🔔 Subscribe to Ram N JavaIntroduction
Serialization in Java is governed by clear runtime rules that determine how an object's state is captured, stored, and restored. Overlooking these fundamental rules often results in unexpected exceptions such as NotSerializableException or InvalidClassException. In this tutorial, we break down the critical rules you must follow when working with Java IO serialization.
Essential Rules of Java Serialization
1. The Serializable Contract
For any object to be serialized, its class must implement the java.io.Serializable marker interface. If you attempt to pass an object that does not implement this interface to ObjectOutputStream.writeObject(), the JVM throws a runtime NotSerializableException.
2. Inheritance Rules
- Superclass implements Serializable: If a parent class implements
Serializable, all child subclasses automatically inherit serializability without needing to declare the interface explicitly. - Superclass does NOT implement Serializable: If the subclass implements
Serializablebut its parent does not, the non-serializable superclass must have an accessible no-argument constructor. During deserialization, that superclass constructor executes to initialize the inherited state.
3. Handling Static and Transient Members
Serialization captures only instance state:
staticfields: Belong to the class definition rather than the object instance, so they are never saved into the byte stream.transientfields: Specifically flagged to skip serialization. When reconstructed, they receive default initial values (such asnull,0, orfalse).
4. Complete Object Graphs
If a serializable class contains references to other custom objects (HAS-A relationship), every single referenced object must also be serializable. If even one referenced object lacks the Serializable interface, the entire serialization process fails.
Quick Reference Summary
| Component | Serialization Rule |
|---|---|
| Serializable Interface | Mandatory; otherwise throws NotSerializableException |
| serialVersionUID | Recommended to explicitly declare to prevent version mismatches |
| Static / Transient | Both are ignored during the serialization process |
| Non-serializable Superclass | Must provide an accessible no-arg constructor |
Related Tutorials from Ram N Java
Click here to watch in Youtube :
https://www.youtube.com/watch?v=H4ZkBxp06kU&list=UUhwKlOVR041tngjerWxVccw
Click the below Image to Enlarge
![]() |
| Java Tutorial : Java IO (Java Serialization rules) |

No comments:
Post a Comment