When serialization encounters inheritance...
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.
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.