• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Could somebody explain this to me?

 
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please consider the following Java Program:

import java.io.*;

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

public class CardPlayer extends Player implements Serializable {
CardPlayer()
{ 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 );
os.writeObject(c1);
os.close();
FileInputStream fis = new FileInputStream( "play.txt" );
ObjectInputStream is = new ObjectInputStream( fis );
System.out.println( "before" );
CardPlayer c2 = (CardPlayer) is.readObject();
System.out.println( "after" );
is.close();
} 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.

Thanks
Bob

~
~
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic