How serialization works when only subclass implements serializable

后端 未结 3 1979
悲哀的现实
悲哀的现实 2020-12-14 01:48

Only subclass has implemented Serializable interface.

import java.io.*;

public class NewClass1{

    private int i;
    NewCla         


        
3条回答
  •  北海茫月
    2020-12-14 02:05

    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.

提交回复
热议问题