• 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

Inheritance affecting deserialization

 
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,
I am preparing for SCJP6 and somewhere(not in KB book) I read that

"For an object to be deserialized properly, the first superclass in its inheritance hierarchy that doesn't implement serializable must have a no-arg constructor.If not, the readObject() method of ObjectInputStream throws a java.io.InvalidClassException."

If we observe this statement is true because Object class which doesn't implement serializable has a no-arg constructor.

I haven't found this mentioned in K&B book.Can anybody throw light on this?

Thanks!
 
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi.
Lets suppose you have the following Hierarchy:

java.lang.Object
|
|
MyClass (DOES NOT IMPLEMENT SERIALIZABLE!)
|
|
HisClass (Implements serializable)

Ok, so HisClass extends MyClass which DOES NOT implement the java.io.Serializable interface. When you serialize an object
of type HisClass any variable inherited from MyClass will NOT
be serialized as the MyClass class doesn't implement Serializable.
Now, you deserialize the HisClass object. Since MyClass doesn't implement
serializable, it's constructor will be invoked. And I am guessing that
the call to invoke MyClass constructor will be a no-arg call.
So if you have a constructor in MyClass like:


The compiler will NOT insert a default constructor at compile time (all it will insert is a call to super unless you already have it in the constructor or if you have an explicit call to an overloaded constructor - this()), which would look like (if it was inserted by the compiler) with a default call to super (java.lang.Object) which is fine.
So I am assuming a runtime exception will be thrown at runtime as the JVM tries to invoke MyClass() which won't exist.
Are you with me?
K
[ June 26, 2008: Message edited by: Keith Nagle ]
 
I can't beleive you just said that. Now I need to calm down with this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic