| Author |
Serialization Code from K&B Book
|
Srinivas Katta
Ranch Hand
Joined: Feb 01, 2007
Posts: 74
|
|
Hi All,
I have executed the below code
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);
CardPlayer c2 = (CardPlayer) is.readObject();
is.close();
} catch (Exception x ) { }
}
}
and the result is "pcp" as per the book.
But I remember from the book " When an instance of
a serializable class is deserialized, the constructor does not run, and instance variables
are NOT given their initially assigned values!"
If the above is true the result should print as "p" only
Please let me know if anybody have different understanding
Thanks
Srinivas
|
 |
Abimaran Kugathasan
Ranch Hand
Joined: Nov 04, 2009
Posts: 2066
|
|
Please UseCodeTags when you post question.
When you create an instance of CardPlayer c1, pc will be printed and when you deserialized, sine your super Player class doesn't implement Serializable, so its Constructor will be invoked.
|
|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
|
 |
 |
|
|
subject: Serialization Code from K&B Book
|
|
|