• Post Reply Bookmark Topic Watch Topic
  • New Topic

problem in output when using ObjectOutputStream .  RSS feed

 
sreenivas jeenor
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ALL,

I have one doubt.

Here is My program
-----------------------


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

}

}
-------------------------------


if i run this program the out put is 'PCP'. What I thought is 'PC'. How it is getting "PCP".

Thanks
[ July 23, 2007: Message edited by: sreenivas jeenor ]
 
vanlalhmangaiha khiangte
Ranch Hand
Posts: 170
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class CardPlayer extends Player implements Serializable

If you remove "implements Serializable"
then the output will be PC
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by vanlalhmangaiha khiangte:

If you remove "implements Serializable"
then the output will be PC


For the love of Pete! If he removes "implements Serializable", then the output will include a stack trace. Is this Bad Answer Day here at the Ranch, and nobody told me about it?

When an object is deserialized, no constructor is executed for the Serializable parts of the object. If a Serializable class extends a non-serializable one, though, then the default constructor of the highest non-serializable class (here, "Player") does in fact get executed.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!