How does the below code work?
class A {
int a = 10;
}
class B extends A implements Serializable{
}
public class Test {
public static void main(String[] args){
B obj = new B();
obj.a = 25;
//Code to serialize object B (B b= new B()),
// deserialize it and print the value of 'a'.
}
}
The code prints 10 even though I have changed the value of 'a' in the code.
Any explanation for this behaviour ?
You can't serialise a class that doesn't implement Serializable , but you can wrap it in a class that does. To do this, you should implement readObject and writeObject on your wrapper class so you can serialise its objects in a custom way.
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.
In order to prevent subclass from serialization we need to implement writeObject() and readObject() methods which are executed by JVM during serialization and deserialization also NotSerializableException is made to be thrown from these methods.
It'll throw a NotSerializableException when you try to Serialize it. To avoid that, make that field a transient field. Save this answer.
If you are a serializable class, but your superclass is NOT serializable, then any instance variables you INHERIT from that superclass will be reset to the values they were given during the original construction of the object. This is because the non- serializable class constructor WILL run! In fact, every constructor ABOVE the first non-serializable class constructor will also run, no matter what, because once the first super constructor is invoked, (during deserialization), it of course invokes its super constructor and so on up the inheritance tree.
The default value of a
is 10 - it will be set to 10 when the object is created. If you want to have a realistic test, set it to a different value after instantiation and then serialize it.
As for your update - if a class is not serializable, its fields are not serialized and deserialized. Only the fields of the serializable subclasses.
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