Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing child class if parent class does not implement serializable?

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?

like image 314
emilly Avatar asked Dec 09 '13 16:12

emilly


People also ask

What will happen if parent class is not serializable?

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.

What will happen if we don't implement serializable?

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.

How can you prevent a child class from being serialized when it's parent class implements serializable interface?

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.

When a child class can be serialized the parent class can be automatically serialized?

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. }


1 Answers

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).

like image 197
chrylis -cautiouslyoptimistic- Avatar answered Sep 21 '22 20:09

chrylis -cautiouslyoptimistic-