• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ObjectInputStream and default constructor in Tiger

 
Leonardo Crespo
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Joyce Lee
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that a 'no-arg constructor' and a 'default constructor' are not the same thing.

JLS 8.8.7 for more information.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic