M_x_r
M_x_r

Reputation: 604

Why is the first constructor called after deserialization and no others

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 ) { }
 }
}

Upvotes: 1

Views: 276

Answers (2)

dcernahoschi
dcernahoschi

Reputation: 15250

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.

Upvotes: 4

Amit Deshpande
Amit Deshpande

Reputation: 19185

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.

Upvotes: 1

Related Questions