If a class is serializable, it means that object of that class can be converted into a sequence of bits so that it can be written to some storage medium or even transmitted over a network without any change in object.
Notice that for a class to be serialized successfully, two conditions must be met:
Notice that for a class to be serialized successfully, two conditions must be met:
- The class must implement the java.io.Serializable interface.
- All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient. - Any transient variable that was part of object will not saved to the file.
public class Employee implements java.io.Serializable { public String name; public String address; public transient int SSN; public int number; public void mailCheck() { System.out.println("Mailing a check to " + name + " " + address); } }
Key points to be remember:
- Any static variable cannot be serialized.
- If base class is serialized, child class would also do.
- If base class is not serialized and child class is serialized then NonSerializableException occurs.
Serializing an Object
The ObjectOutputStream class is used to serialize an Object. The following demo program instantiates an Employee object and serializes it to a file.
When the program is done executing, a file named employee.ser is created. The program does not generate any output, but study the code and try to determine what the program is doing.
Note: When serializing an object to a file, the standard convention in Java is to give the file a.ser extension.
import java.io.*; public class Demo { public static void main(String [] args) { Employee e = new Employee(); e.name = "Tarun Solanki"; e.address = "Sector-135, Noida"; e.SSN = 1333333; e.number = 12; try { FileOutputStream fileOut = new FileOutputStream("/tmp/employee.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(e); out.close(); fileOut.close(); System.out.printf("Serialized data is saved in /tmp/employee.ser"); }catch(IOException i) { i.printStackTrace(); } } }