🚀 Ready to Master Java?
Don't miss out on more easy-to-follow coding tutorials. Join our growing community today!
SUBSCRIBE TO RAM N JAVAJava Serialization with IS-A (Inheritance)
Welcome back! Today, we are diving deep into how Serialization works when Inheritance (IS-A relationship) is involved. This is a common topic in interviews and a must-know for any Java developer working with object persistence.
What is the IS-A Relationship in Serialization?
In Java, when a child class inherits from a parent class, it is known as an IS-A relationship. When it comes to Serialization, the main question is: If a parent class is serializable, is the child class also serializable? Let’s look at the different scenarios.
Scenario 1: Parent Class Implements Serializable
If a Parent class implements the java.io.Serializable interface, then every Child class that extends it automatically becomes serializable. You don't need to explicitly implement the interface in the child class. This is because the serializable property is inherited.
Scenario 2: Parent is NOT Serializable, but Child IS
This is a tricky part! If the Parent class does not implement Serializable, but the Child class does, you can still serialize the Child object. However, there are specific rules:
- During deserialization, Java will run the default constructor of the non-serializable Parent class.
- Any fields inherited from the non-serializable Parent will be reset to their default values (e.g., 0 for int, null for objects).
- Important: The Parent class must have a no-argument constructor; otherwise, a
InvalidClassExceptionwill be thrown.
Key Takeaways for Beginners
- Inheritance Matters: If the base class is serializable, all subclasses are too.
- Constructor Rule: Always check if your non-serializable parent classes have a default constructor if you plan to serialize the children.
- Data Loss: Be careful with non-serializable parents, as their specific state won't be saved during the process.
Watch More from Ram N Java:
Keep learning with these related Java IO tutorials:
Click here to watch in Youtube :
https://www.youtube.com/watch?v=Ww7W_VLVgHQ&list=UUhwKlOVR041tngjerWxVccw
Click the below Image to Enlarge
![]() |
| Java Tutorial : Java IO (Java Serialization with IS A Inheritance) |


No comments:
Post a Comment