• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how FileOutputStream and ObjectOutputStream working here

 
pawni jain
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello ranchers
please explain me how the FileOutputStream and ObjectOutputStream working in the following code..

import java.io.*;
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);
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 ) { }
}
}

output:
pcp

Thanks,
Regards.
 
amitabh mehra
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello Amitabh

Thanks for explaining the reason.I got the concept.


Thanks ,
Regards.
 
Rob Spoor
Sheriff
Pie
Posts: 20610
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic