File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Could somebody explain this to me? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Could somebody explain this to me?" Watch "Could somebody explain this to me?" New topic

Could somebody explain this to me?

Bob Sherry

Joined: Jun 27, 2008
Posts: 20
Please consider the following Java Program:


class Player {
{ System.out.println( "base called" ); }

public class CardPlayer extends Player implements Serializable {
{ System.out.println( "dev called" ); }
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 );
System.out.println( "before" );
CardPlayer c2 = (CardPlayer) is.readObject();
System.out.println( "after" );
} catch ( Exception x ) { }

When the object is read back off the disk, I would expect that there would
be a call to the constructor for CardPlayer and a call to the constructor for Player. However, I am only getting the constructor call for Player. I am hoping that somebody can tell why this is.


Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

Hi Bob,

Welcome to JavaRanch!

Basically because Player is not serializable, and CardPlayer is. A Serializable instance is normally deserialized without calling its constructor. But if the base class isn't serializable, the serialization mechanism won't store its state; instead, the base part of the object will be initialized with a constructor call.

If you mark Player as Serialized, you'll see that printout disappear.

[Jess in Action][AskingGoodQuestions]
I agree. Here's the link:
subject: Could somebody explain this to me?
It's not a secret anymore!