Java object Serialization and inheritance

随声附和 提交于 2019-11-27 19:19:42
paulsm4

Serializable is just a "marker interface" for a given class.

But that class must adhere to certain rules:

http://docs.oracle.com/javase/1.5.0/docs/api/java/io/Serializable.html

To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable if this is not the case.

to answer @Sleiman Jneidi question asked in comment, in oracle documentation mentioned above, its clearly mentioned

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.

Thus, default no-arg constructor of class Foo called of, resulted in initialization.

it may be that the defaultWriteObject can only write the non-static and non-transient fields of the current class. Once the superclass does not implements the Serializable interface, the fields in the superclass can not be serialized into the stream.

Actually when you will read the parent class object back as it's not serialize at all.. so for the non serialize things again JVM go through the same process as it use to go when we create the new object using new keyword.

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