Win a copy of Java Concurrency Live Lessons this week in the Threads forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

will subclass gets serialized?  RSS feed

 
prashanth mallik
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If class A implements serializable ,then does class B which is subclass of class A also gets serialized?
 
Jerry Pulley
Ranch Hand
Posts: 221
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Prashanth,
Yes, all subclasses of a serializable class are also serializable.
Jerry
 
prashanth mallik
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it other way also, i mean to say
If Class B implements Serializable, does Class A super class of class B also serialized.


 
prashanth mallik
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


[This message has been edited by prashanth mallik (edited January 22, 2001).]
 
Jerry Pulley
Ranch Hand
Posts: 221
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Prashanth,
Man, I thought I was going to get off easy on this one.
No, the non-serializable superclass of a serializable class is not serialized. Notice I say "the", not "a", because at some point in every class's parentage there is a non-serializable class - Object is not serializable.
There are a couple of points to address here:
1) Suppose C is serializable and B, its immediate superclass, is not. Then B must provide a no-argument constructor, and the constructor must be accessible by C. When C is deserialized, B() will be called to construct the superclass part of C's state. If B doesn't have such a c'tor, deserializing C will throw an InvalidClassException. You won't see any problems when you serialize C, only when you attempt to deserialize it.
2) It is possible to include superclass fields in serialization by overriding writeObject() and readObject() in the serializable class, so long as the fields are accessible. These methods give you the opportunity to save and restore superclass state beyond the default values provided by the superclass's no-arg c'tor.
Jerry
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!