• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Deserializing

 
Higgledy Smith
Ranch Hand
Posts: 192
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given:
import java.io.*;
class Player {
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);
1 CardPlayer c2 = (CardPlayer) is.readObject();
is.close();
} catch (Exception x ) { }
}
}

Why does Player() constructor get called at 1? I thought constructors were not called during deserialization?

(Chapter 6 sucks for me.)
 
J Sato
Ranch Hand
Posts: 40
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try pages 455. Since class Player is the parent class of CardPlayer and it DOES NOT implement Serializable, its constructor runs.

...and if ch 6 is bad, wait until you get to 7. (at least for me anyways)
[ March 30, 2006: Message edited by: J Sato ]
 
Mark Spritzler
ranger
Sheriff
Posts: 17276
6
IntelliJ IDE Mac Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Think about it this way, since the Parent is not Serializable, then the inherited variables from the parent are not saved when the child object is serialized. So in that case, when the child is de-serialized, those inherited variables need to be reset to their default values and their no-args constructor is called.

Mark
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic