Java object Serialization and inheritance

前端 未结 3 823
灰色年华
灰色年华 2020-12-05 04:36

Say you have these two classes, Foo and Bar where Bar extends Foo and implements Serializable

class Foo {

public String name;

public Foo() {
          


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-05 05:25

    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.

提交回复
热议问题