Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing an object which has a non-serializable parent class

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 ?

like image 343
Vinoth Kumar C M Avatar asked Jul 11 '11 11:07

Vinoth Kumar C M


People also ask

How do you serialize an object that is not serializable?

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.

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

How do you make child class non-serializable if parent class is serializable?

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.

What happens if your serializable class contains a member which is not serializable?

It'll throw a NotSerializableException when you try to Serialize it. To avoid that, make that field a transient field. Save this answer.


2 Answers

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.

like image 71
Vasu Avatar answered Oct 01 '22 14:10

Vasu


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.

like image 34
Bozho Avatar answered Oct 01 '22 12:10

Bozho