1. What is serialization?
This is simply to preserve the state of various objects in memory (i.e., instance variables, not methods), and to read the saved object state again. Although you can save object states in a variety of ways, Java provides you with a mechanism that should be better than your own to preserve the state of objects, which is serialization.
2. What situations require serialization
A) When you want to save the state of an object in memory in a file or in a database;
b) When you want to use sockets to transfer objects on the network;
c) When you want to transfer objects through RMI;
Package Cn.sdl.serializable;import Java.io.filenotfoundexception;import java.io.fileoutputstream;import Java.io.objectoutputstream;import java.io.Serializable; Public classBox implements serializable{Private intwidth; Private intheight; Public voidSetWidth (intwidth) { This. width =width; } Public voidSetHeight (intheight) { This. Height =height; } Public Static voidMain (string[] args) {box box=NewBox (); Box.setheight ( One); Box.setwidth ( A); Try{FileOutputStream fs=NewFileOutputStream ("D:/foo.ser"); ObjectOutputStream OS=NewObjectOutputStream (FS); Os.writeobject (box); Os.close (); } Catch(Exception e) {e.printstacktrace (); } }}
My understanding and summary of Java Serializable (serialization)--Go