Contents
How does inheritance affect serialization?
Serialization is a mechanism of converting the state of an object into a byte stream. There are some cases of Serialization with respect to inheritance : Case 1: If superclass is serializable then subclass is automatically serializable : If superclass is Serializable, then by default every subclass is serializable.
Can we serialize abstract class?
However, even though most abstract classes don’t implement Serializable , they may still need to allow their subclasses to do so, if desired. If the abstract class has no state, then it can simply provide a no-argument constructor to its subclasses.
Can serializable class inherited?
NonSerializedAttribute Class (System) Indicates that a field of a serializable class should not be serialized. This class cannot be inherited.
What happens if my parent class doesn’t implement serialization and child class does?
An instance of Parent can be serialized, but an instance of Child cannot because it has an attribute whose type ( Thread ) does not implement Serializable . (Now if t was declared as transient , or if Child avoided using the default serialization mechanism, Child could be made to be serializable.
How can we prevent serialization?
To avoid Java serialization you need to implement writeObject() and readObject() method in your Class and need to throw NotSerializableException from those method.
Can we serialize class without implementing Serializable interface?
Only subclasses of the Serializable interface can be serialized. If our class does not implement Serializable interface, or if it is having a reference to a non- Serializable class, then the JVM will throw NotSerializableException .
Can we serialize child class?
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. }