rspec/rules/S2055/java/rule.adoc

70 lines
1.9 KiB
Plaintext

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.
== Noncompliant Code Example
----
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() {...}
}
----
== Compliant Solution
----
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() {...}
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
'''
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]