File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Deserializing Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Deserializing " Watch "Deserializing " New topic


Higgledy Smith
Ranch Hand

Joined: Mar 07, 2006
Posts: 192
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);
FileInputStream fis = new FileInputStream("play.txt");
ObjectInputStream is = new ObjectInputStream(fis);
1 CardPlayer c2 = (CardPlayer) is.readObject();
} 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

Joined: Mar 30, 2006
Posts: 40
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

Joined: Feb 05, 2001
Posts: 17276

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.


Perfect World Programming, LLC - iOS Apps
How to Ask Questions the Smart Way FAQ
I agree. Here's the link:
subject: Deserializing
It's not a secret anymore!