简体   繁体   中英

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?

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.

Since B extends A , it is an A . This means that b instanceof Serializable returns true .

So, as long as the object you try to serialize returns true for the instanceof Serializable checks, you can serialize it. This applies for any composite objects contained within this object itself.

But you can't do A a = new A(); and attempt to serialize a .

Consider this:

java.lang.Object doesn't implement Serializable . So, no one would've been able to serialize any objects in Java in that case, However. that's not the case at all, Also, in projects where there are multiple JavaBeans involved that extend a common super type, the general practice is to make this super type implement Serializable so that all the sub classes don't have to do that.

If class B extends class A, and A is not serializable, then all the instance variables of class A are initialized with their default values (which is 10 in this case) after de-serialization of class B.

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.

If a parent class is not serializable its fields are initialised each time the object is deserialized. ie The object still needs to be constructed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM