When a Serializable
object has a non-serializable ancestor in its inheritance chain, object deserialization (re-instantiating the
object from file) starts at the first non-serializable class, and proceeds down the chain, adding the properties of each subsequent child class, until
the final object has been instantiated.
In order to create the non-serializable ancestor, its no-argument constructor is called. Therefore the non-serializable ancestor of a
Serializable
class must have a no-arg constructor. Otherwise the class is Serializable
but not deserializable.
public class Fruit { private Season ripe; public Fruit (Season ripe) {...} public void setRipe(Season ripe) {...} public Season getRipe() {...} } public class Raspberry extends Fruit implements Serializable { // Noncompliant; nonserializable ancestor doesn't have no-arg constructor private static final long serialVersionUID = 1; private String variety; public Raspberry(Season ripe, String variety) { ...} public void setVariety(String variety) {...} public String getVarity() {...} }
public class Fruit { private Season ripe; public Fruit () {...}; // Compliant; no-arg constructor added to ancestor public Fruit (Season ripe) {...} public void setRipe(Season ripe) {...} public Season getRipe() {...} } public class Raspberry extends Fruit implements Serializable { private static final long serialVersionUID = 1; private String variety; public Raspberry(Season ripe, String variety) {...} public void setVariety(String variety) {...} public String getVarity() {...} }