Tuesday, 4 October 2016

Java Tutorial : Java IO (Java Serialization rules)

🚀 Enjoying Java Tutorials?

Subscribe to Ram N Java for clean, beginner-friendly core Java tutorials and interview prep!

🔔 Subscribe to Ram N Java

Introduction

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 Serializable but 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:

  • static fields: Belong to the class definition rather than the object instance, so they are never saved into the byte stream.
  • transient fields: Specifically flagged to skip serialization. When reconstructed, they receive default initial values (such as null, 0, or false).

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) 
See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • No comments:

    Post a Comment

    Tutorials