It's not a secret anymore!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Inheritance affecting deserialization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Inheritance affecting deserialization" Watch "Inheritance affecting deserialization" New topic

Inheritance affecting deserialization

Swathi Kota
Ranch Hand

Joined: Jun 04, 2008
Posts: 52
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"

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?


Success is how high you bounce when you hit bottom
Keith Nagle
Ranch Hand

Joined: May 06, 2008
Posts: 65
Lets suppose you have the following Hierarchy:

HisClass (Implements serializable)

Ok, so HisClass extends MyClass which DOES NOT implement the 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?
[ June 26, 2008: Message edited by: Keith Nagle ]

SCJP 5.0
I agree. Here's the link:
subject: Inheritance affecting deserialization
It's not a secret anymore!