aspose file tools
The moose likes I/O and Streams and the fly likes how  FileOutputStream and ObjectOutputStream working here Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide 1Z0-808 this week in the OCAJP forum!
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "how  FileOutputStream and ObjectOutputStream working here" Watch "how  FileOutputStream and ObjectOutputStream working here" New topic

how FileOutputStream and ObjectOutputStream working here

pawni jain

Joined: Apr 10, 2008
Posts: 22
hello ranchers
please explain me how the FileOutputStream and ObjectOutputStream working in the following code..

class Player {
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);
FileInputStream fis = new FileInputStream("play.txt");
ObjectInputStream is = new ObjectInputStream(fis);
CardPlayer c2 = (CardPlayer) is.readObject();
} catch (Exception x ) { }


amitabh mehra
Ranch Hand

Joined: Dec 05, 2006
Posts: 98
1) A class can be serialized even if its parent class is not.
2) When an instance of a Serializable class is deserialized, the constructor does not run, and instance variables arc not given their initially assigned values.
3) If your class is a serializable class, but your superclass is not serializable, then the non-serializable class constructor will run when the object for child class is getting deserialized. Every constructor above the first non-serializable class constructor will also run, no matter what, because once the first super constructor is invoked, it of course invokes its super constructor and so on up the inheritance tree

For the output:
The first 'p' and 'c' in the output are simple - super class constructor and class constructor getting called while object creation of class CardPlayer in:
CardPlayer c1 = new CardPlayer();

The last p is because of point 3 stated above.
pawni jain

Joined: Apr 10, 2008
Posts: 22
hello Amitabh

Thanks for explaining the reason.I got the concept.

Thanks ,
Rob Spoor

Joined: Oct 27, 2005
Posts: 19845

One addition to amitabh's explanation:

Only the constructor without parameters is called for the direct super class. If there is none you will get an InvalidClassException, which is an indirect subclass of IOException.

For example:

Class C can be serialized and deserialized without a problem. However, once you omit line 1, it can only be serialized.

How To Ask Questions How To Answer Questions
I agree. Here's the link:
subject: how FileOutputStream and ObjectOutputStream working here