The main function of serialization in Java is to lossless the instance of a class, or it is through the Java serialization mechanism that instances of Java classes can be transmitted and retrieved through an object stream without damaging instances of the class.
First, let's look at what class is a serialized class,
The 1.A class itself implements the Serializable interface;
The 2.A class itself does not implement the Serializable interface, but its parent class implements the class of the Serializable interface;
Both of the above, we think that Class A is a serialization class.
In the SCJP exam there is a topic of serialization:
import Java.io.FileInputStream; Import Java.io.FileOutputStream; Import Java.io.ObjectInputStream; Import Java.io.ObjectOutputStream; Import java.io.Serializable; Class Food {Food () {System.out.print ("1")}} class Fruit extends Food implements Serializable {Fruit () {SYSTEM.OUT.P Rint ("2"); } public class Banana2 extends Fruit {int size = n. public static void Main (string[] args) {Banana2 b = new Banana2 () ; B.serializebanana2 (b); Assume correct serialization B = B.deserializebanana2 (b); Assume correct System.out.println ("restored" + B.size + "");} More BANANA2 methods public static void SerializeBanana2 (Banana2 b) {try {objectoutputstream out = new OBJECTOUTPUTST Ream (New FileOutputStream ("C:/a.txt")); Out.writeobject (b); catch (Exception e) {e.printstacktrace ();}} public static Banana2 DeserializeBanana2 (Banana2 b) {try {objectinputstream in = new ObjectInputStream (New Fileinputstre AM ("c:/a.txt")); Return (BANANA2) in.readobject (); catch (Exception e) {e.printstacktrace ();} return null; }}
The output of this problem is: 121 restored 42
From the results of the operation: the previous number 12 is obvious, at the time of the new Banana2 (), but the third 1 is not understood, in fact, if from a polymorphic point of view, it is not difficult to understand, because deserialization is to get the original class instance, This requires that a primitive class or an instance of the parent class of the original class be declared before deserialization, and that the parent class (base class) declaration is easy to understand when considering the mechanism of Java polymorphism.
Of course, this also has a corresponding requirement for the parent class, if Class A implements the serialization interface, A's parent class does not implement the serialization interface, then, when deserializing an instance of a, it first executes the parameterless construction of A's parent class, so this requires that the parent class of a must have an parameterless constructor, or an error. If the parent class also implements the serialization interface, the parent class construct will not be executed at deserialization time.