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?
SCJP 6, SCWCD 5
Success is how high you bounce when you hit bottom
Joined: May 06, 2008
Hi. Lets suppose you have the following Hierarchy:
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 ]