Serialization inheritance in J2SE

Source: Internet
Author: User

When a parent class implements the Serializable interface, its sub-classes are automatically serialized.

This is verified as follows:

Package Serial;
Import java. io. Serializable;
Public class SuperC implements Serializable {// The parent class implements serialization.
Int supervalue;
Public SuperC (int supervalue ){
This. supervalue = supervalue;
}
Public String toString (){
Return "supervalue:" + supervalue;
}
}

Public class SubC extends SuperC {// subclass
Int subvalue;

Public SubC (int supervalue, int subvalue ){
Super (supervalue );
This. subvalue = subvalue;
}

Public String toString (){
Return super. toString () + "sub:" + subvalue;
}
}

Public class Test1 {

Public static void main (String [] args ){
SubC subc = new SubC (100,200 );
FileInputStream in = null;
FileOutputStream out = null;
ObjectInputStream oin = null;
ObjectOutputStream oout = null;
Try {
Out = new FileOutputStream ("Test1.txt"); // serialization of sub-classes
Oout = new ObjectOutputStream (out );
Oout. writeObject (subc );
Oout. close ();
Oout = null;

In = new FileInputStream ("Test1.txt ");
Oin = new ObjectInputStream (in );
SubC subc2 = (SubC) oin. readObject (); // subclass deserialization
System. out. println (subc2 );
} Catch (Exception ex ){
Ex. printStackTrace ();
} Finally {
... Omitted here
}
}
}

The running result is as follows:

Supervalue: 100 sub: 200

We can see that the subclass has been serialized/deserialized successfully.

How to make the subclass implement serialization seems very simple, but sometimes we often cannot let the parent class implement the Serializable interface, the reason is that sometimes the parent class is abstract (this does not matter), and the parent class cannot force each subclass to have the serialization capability. In other words, the parent class is designed to be inherited.

Writing a Serializable subclass is troublesome for a parent class that does not implement the Serializable interface. Java docs mentioned:

"To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields. 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."

That is to say, to compile a Serializable subclass for a parent class that does not implement the Serializable interface, we need to do two things:

1. The parent class must have a constructor without parameters;

Second, the subclass is responsible for serializing (deserializing) the domain of the parent class.

We remove the Serializable interface of SuperC and add the Serializable interface to SubC. Errors generated after running:

Java. lang. Error: Unresolved compilation problem:
Serializable cannot be resolved or is not a valid superinterface
At Serial. SubC. (SubC. java: 15)
At Serial. Test1.main (Test1.java: 19)
Exception in thread "main"

As mentioned in docs, the absence of a no-argument constructor in the parent class does not work.

Next, follow the suggestions in docs to rewrite this example:

Public abstract class SuperC {
Int supervalue;
Public SuperC (int supervalue ){
This. supervalue = supervalue;
}
Public SuperC () {}// Add a constructor without Parameters
Public String toString (){
Return "supervalue:" + supervalue;
}
}

Public class SubC extends SuperC implements Serializable {
Int subvalue;

Public SubC (int supervalue, int subvalue ){
Super (supervalue );
This. subvalue = subvalue;
}

Public String toString (){
Return super. toString () + "sub:" + subvalue;
}

Private void writeObject (java. io. ObjectOutputStream out)
Throws IOException {
Out. defaultWriteObject (); // serialize the object first
Out. writeInt (supervalue); // deserialize the parent class domain
}
Private void readObject (java. io. ObjectInputStream in)
Throws IOException, ClassNotFoundException {
In. defaultReadObject (); // deserialize the object first
Supervalue = in. readInt (); // deserialize the domain of the parent class
}
}

The running result proves that this method is correct. Here we use the writeObject/readObject method. If this method exists, it will be called during serialization to replace the default behavior (we will discuss it later and learn more ). During serialization, we first call the defaultWriteObject of ObjectOutputStream, which uses the default serialization behavior and then serializes the parent class domain. This is also true for deserialization.

To sum up:

Target Behavior

For a parent class that implements the Serializable interface, compile a subclass class that can be serialized to automatically implement serialization.

For a parent class that does not implement the Serializable interface, write a Serializable subclass 1. The parent class must have a constructor without parameters; 2. The subclass must first serialize itself, then the subclass is responsible for serializing the parent class's domain.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.