| Author |
doubt based on construtor
|
sankar kandasamy
Greenhorn
Joined: Sep 13, 2007
Posts: 13
|
|
I saw one question in SCJP model question. The question: 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 ) { } } } For this question I guess the answer as pc but it gives the answer as: pcp I cant understand how this answer comes. I cant understand when the base class contrutor secone time called pls help me
|
 |
Praveen Seluka
Ranch Hand
Joined: Jul 17, 2007
Posts: 95
|
|
Hi Note that superclass player is not serialized while subclass cardplayer is serialized.generally when deserializing the constructor doesnt run.But in this case,as the super class player does not implement serializable,the Objects state would not have been stored during serialization. So when deserializing the superclass constructor runs,and sets player to its initial state. Thanks Praveen SP
|
 |
Abhishek khare
Greenhorn
Joined: Aug 08, 2007
Posts: 25
|
|
CardPlayer c2 = (CardPlayer) is.readObject(); at this POINT the when you deserealize the Object C2(CardPlayer) is deserealized but however since Player does not implement Serializable its constructor will be called. change code to import java.io.*; class Player implements Serializable { Player() { System.out.print("p"); } } public 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 you wil get O/P as "pc" Hope it helps
|
"Things come to those who wait, but only the things left by those who hustle."
|
 |
Yogvinder Singh Ghotra
Ranch Hand
Joined: Sep 10, 2007
Posts: 38
|
|
|
Moreover, i think only the default no arg constructor is called during de-serialization.
|
 |
sankar kandasamy
Greenhorn
Joined: Sep 13, 2007
Posts: 13
|
|
|
I got it . Thanks for all
|
 |
 |
|
|
subject: doubt based on construtor
|
|
|