Why is the first constructor called after deserialization and no others

本小妞迷上赌 提交于 2019-12-24 16:12:50

问题


please can someone explain why the constructor of the class 'Gambler' is called after deserialization but say the constructor of the class 'Player' is not?

import java.io.*;
  class Gambler {
   Gambler() { System.out.print("d"); }
  }
  class Person extends Gambler implements Serializable {
   Person() { System.out.print("c"); }
  }
  class Player extends Person {
   Player() { System.out.print("p"); }
 }

  class CardPlayer extends Player implements Serializable {
    CardPlayer() { System.out.print("c"); }
      public static void main(String[] args) {
      CardPlayer c1 = new CardPlayer();
      try {
            FileOutputStream fos = new FileOutputStream("play.txt");
            ObjectOutputStream os = new ObjectOutputStream(fos);
            os.writeObject(c1);
            os.close();
            FileInputStream fis = new FileInputStream("play.txt");
            ObjectInputStream is = new ObjectInputStream(fis);
            CardPlayer c2 = (CardPlayer) is.readObject();
            is.close(); 

            } 
      catch (Exception x ) { }
 }
}

回答1:


Because the Gambler class does not implement the Serializable interface. From javadocs of Serializable:

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. The error will be detected at runtime.

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.

See the java.io.Serializable java docs.




回答2:


While serializing Object Tree is persisted in your case object tree is upto Person class. Now Super() mechanism comes into picture if parent class is not serializable for any child class. so This is why your constructor of Gambler is getting invoked.

You can find More information on http://docs.oracle.com/javase/6/docs/api/java/io/Serializable.html

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.



来源:https://stackoverflow.com/questions/12317063/why-is-the-first-constructor-called-after-deserialization-and-no-others

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