Reputation: 62165
The GWT tutorial says
As of GWT 1.5, it must have a default (zero argument) constructor (with any access modifier) or no constructor at all.
So, when the default constructor is only used by the Serialization mechanism, wouldn't it be useful to make it private
? This way, clients of the class don't accidentally call the default constructor, and the visible interface becomes smaller.
Or does it somehow affects the Serialization mechanism in any other way?
Upvotes: 5
Views: 2262
Reputation: 191
**WARNING THIS ANSWER IS NOT ABOUT HOW THE GWT COMPILER HANDLES ITS REQUIRED DEFAULT NO-ARG CONSTRUCTOR**
If you put it private, Serialization won't work.
From Javadoc : "The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable if this is not the case. The error will be detected at runtime."
So yes, it will affect the Serialization process.
You could deprecate or comment this constructor indicating it is only used for Serialization purpose.
See here for details about serialization.
Upvotes: -2
Reputation: 310903
The GWT tutorial statement appears to apply to a specific requirement of GWT itself, or else it reiterates a common misunderstanding. The Java requirement is that the nearest non-serializable base class has an accessible default constructor. Not the serializable class itself.
Upvotes: 6
Reputation: 1632
the complete process of serialization involves also deserialization, in which the java object will be reconstructed.
Therefore adding a private constructor to a serializable class will not work on the way back (deserialization) and since you can't have both private and public constructors with the same arguments (in GWT case the default - no args - one) stick with the public modifier.
cheers!
Upvotes: 0