Are classes that implement Serializable required to have no-argument constructors?

Tim Rohaly

No. This is a common misconception. The deserialization process does not use the object's constructor - the object is instantiated without a constructor and initialized using the serialized instance data. The only requirement on the constructor for a class that implements Serializable is that the first non-serializable superclass in its inheritence hierarchy must have a no-argument constructor. (See http://www.jguru.com/jguru/faq/view.jsp?EID=34802 for a more complete explanation). This makes sense: deserialization needs to reconstruct the entire object state, which includes the state of any superclasses. If the superclass is not itself serializable, then deserialization needs to instantiate that superclass from scratch - thus the requirement. For example, with the following class:

public class MySerializableClass implements Serializable {
    ...
}
you do not need a no-argument constructor. MySerializableClass meets all requirements because its first non-serializable superclass, Object, has a no-argument constructor. In the following example:
public class MyFirstClass {
}
public class MySecondClass extends MyFirstClass implements Serializable {
    ...
}
MyFirstClass has the default, no-argument constructor, so no other constructor is needed. If, however, MyFirstClass defined constructors which accepted arguments without also explicitly declaring a no-argument constructor, then you would get a NotSerializableExceptin when trying to serialize MySecondClass.

All the requirements for an object that implements Serializable are listed at http://www.jguru.com/jguru/faq/view.jsp?EID=31434.

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact