How serialization works when only subclass implements serializable

孤者浪人 提交于 2019-11-28 19:20:37
radai

according to the Serializable javadoc

During deserialization, the fields of non-serializable classes will be initialized using the public or protected no-arg constructor of the class. A no-arg constructor must be accessible to the subclass that is serializable. The fields of serializable subclasses will be restored from the stream.

also, serialization exception is only thrown if the class being serialized is not serializable. having non-serializable parents is fine (as long as they have a no-arg constructor). Object itself isnt Serializable, and everything extends it. the quote above also explains why you get different values for the value field - the no-arg constructor for the parent class is set, which sets the value field to 10 - the field belongs to the (non-serializable) parent so its value isnt written to/read from the stream.

If your MyClass holds reference to an object of non serializable class you will get NotSerializable exception at run time. To test, modify MyClass so that it holds a reference to an object of NewClass1. If you run again it will throw an exception.

Deserialization is essentially creating an instance of a serializable class and restoring its properties. During this process the constructor of the serializable class is not called. Rather the no arg constructor of first non serializable super class is called.

In your case the no arg constructor of NewClass1 assigns 10 to its instance variable i. So, during deserialization it's printing 10 instead of 20.

I've not tested it, but you shall get a NotSerializableException if serializing the instance of base class. It is the same when your class contains some members that are not Serializable.

Means if you create an object NewClass1 nc1 = new NewClass1(); and try to serialize the obj nc1, you will get the exception that you want.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!