Serialization is a mechanism provided by java to save the state of one or more objects.During serialization, an object is represented as a sequence of bytes which holds the object and all of its instance variables.And once the object is serialized, whenever required it can be again deserialized to retain the object again with the exact same state in memory.Serialization and deserialization is JVM independent and hence an object can be serialized at one platform and the same object can be retained at another platform with the same state.
1. Java serialization mechanism takes care of serializing complete object graph. For example if Department class has any instance varible of let say Employee than Employee class object will also be serialized given that Employee class also implements Serializable.If not, we get a runtime exception as java.io.NotSerializableExcetion.
2. Again if you do not want to serilize Employee object or you don't have control over the Employee Object then it must be declared as a Transient variable during its declaration in Department class.
3. If a superclass is Serializable, then all subclasses of that class automatically implements Serializable implicitly.
ObjectOutputStream and ObjectInputStream are considered to be higher classes in the java.io packages as we already know the lower-level classes , such as java.io.FileOutputStream and java.io.FileInputStream.The mechanism of the basic serialization happens with just two methods one to serialize objects and write them to a stream, and a second to read the stream and deserialize objects.
Here the Department class implements the Serializable interface. Serializable is a marker interface;it has no methods to impement.It is only used to indicate something to compiler or JVM.Department.java
Following is the implementation of class which will really serialize and deserialize the Department Object.The invocation of writeObject() will serialize the object and then also writes the serialized object to a file. Similarly, invocation of readObject() returns an Object, that's why we need to cast it to the Department object.SerializeDept.java
1. All instance variables are assigned to their default values.
2. The constructor is invoked, which immdiately invokes the superclass constructor.
3. Instance variables that are instantiated as part of their declaration are assigned their initial value.
4. The constructor completes.
I hope this article served you that you were looking for. If you have anything that you want to add or share then please share it below in the comment section.
Is this page helpful to you? Please give us your feedback below. We would love to hear your thoughts on these articles, it will help us improve further our learning process.
©2017, DevGlan. All Rights Reserved.
Contact us: email@example.com