*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes ObjectInputStream and default constructor in Tiger 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 "ObjectInputStream and default constructor in Tiger" Watch "ObjectInputStream and default constructor in Tiger" New topic
Author

ObjectInputStream and default constructor in Tiger

Leonardo Crespo
Ranch Hand

Joined: Jul 03, 2005
Posts: 31
Hi all. Can anyone give me a hand on this issue?


In page 338 of Complete Java 2 Certification, Study Guide, 5th edition (Tiger), it says:
-----------
Notice that the readObject() mechanism of ObjectInputStream relies on the existence of
a no-args constructor for any class that implements Externalizable. If an externalizable class
has no no-args constructor, the readObject() method will throw
java.io.InvalidClassException.
-----------

I checked in the API and it says:


However, this is not true.

This is the class i'm serializing and i'm not providing a default constructor. Since i'm providing a constructor, the compiler does not create the default one.

(ps: just to clarify things, Fusca equals Beagle, it's a type of car)


This code compiles just fine and i dont get errors in deserialization either.



Why is that?

Thank you very much. Leonardo.


Leonardo Crespo
Joyce Lee
Ranch Hand

Joined: Jul 11, 2003
Posts: 1392
Hi Leonardo,

Notice that the readObject() mechanism of ObjectInputStream relies on the existence of a no-args constructor for any class that implements Externalizable. If an externalizable class has no no-args constructor, the readObject() method will throw java.io.InvalidClassException.

Here's an example which demostrates an externalizable class without a no-arg constructor:


Without a no-arg constructor, it'll throw InvalidClassException. Now try uncomment the no-arg constructor and run again. It should run without problem.

More examples on Externalization here.

Joyce
[ July 26, 2005: Message edited by: Joyce Lee ]
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Note that a 'no-arg constructor' and a 'default constructor' are not the same thing.

JLS 8.8.7 for more information.


Tony Morris
Java Q&A (FAQ, Trivia)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: ObjectInputStream and default constructor in Tiger
 
Similar Threads
doubt based on construtor
11 K&B questions. Question 6
Deserializing
A question regarding defaultXxxObject()
Nice Serialization Question