public class Employee2 extends Employee1 {}
public class Employee1 extends Employee0 {}
public class Employee0 {}
Now i serialize the Employee2 class and
get the error java.io.NotSerializableException: Employee2
Now if changed Employee1 class def to
public class Employee1 extends Employee0 implements java.io.Serializable {}
it works fine but please note Employee0 still does not implement Serializable
Is it mandatory for Base class has to implement Serializable to serialize the child class? If yes why its mandatory only for Employee1 but not for Employee0 ?
As per my example it looks like yes but as per other articles on net this should not be mandatory. So what i am missing here?
Case 2: If a superclass is not serializable, then subclass can still be serialized. Even though the superclass doesn't implement a Serializable interface, we can serialize subclass objects if the subclass itself implements a Serializable interface.
The Student would not be Serializable, and it will act like a normal class. Serialization is the conversion of an object to a series of bytes, so that the object can be easily saved to persistent storage or streamed across a communication link.
If superClass has implemented Serializable that means subclass is also Serializable (as subclass always inherits all features from its parent class), for avoiding Serialization in sub-class we can define writeObject() method and throw NotSerializableException() from there as done below.
Yes. If a parent implements Serializable then any child classes are also Serializable . static class A implements Serializable { } static class B extends A { } public static void main(String[] args) { Serializable b = new B(); // <-- this is a legal statement. }
If you want to serialize an Employee2
object, Employee2
has to implement Serializable
(preferably directly rather than inheriting it). You weren't getting the exception because Employee1
isn't serializable, you were getting it because Employee2
isn't, and you tried to serialize it anyway.
Employee1
and Employee0
don't necessarily have to implement Serializable
, but if they don't, they have to have no-argument constructors (so that the serializer can instantiate the reconstructed Employee2
object).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With