What is meant by \"object serialization\"? Can you please explain it with some examples?
Daring to answer the 6-year-old question, adding just a very high-level understanding for people new to Java
What is Serialization?
Converting an object to bytes
What is Deserialization?
Converting bytes back to an object (Deserialization).
When is serialization used?
When we want to Persist the Object. When we want the object to exist beyond the lifetime of the JVM.
Real World Example:
ATM: When the account holder tries to withdraw money from the server through ATM, the account holder information like withdrawal details will be serialized and sent to the server where the details are deserialized and used to perform operations.
How serialization is performed in java.
Implement java.io.Serializable
interface (marker interface so no method to implement).
Persist the object: Use java.io.ObjectOutputStream
class, a filter stream which is a wrapper around a lower-level byte stream (to write Object to file systems or transfer a flattened object across a network wire and rebuilt on the other side).
writeObject(<>)
- to write an object readObject()
- to read an serialized ObjectRemember:
When you serialize an object, only the object's state will be saved, not the object's class file or methods.
When you serialized a 2-byte object, you see 51 bytes serialized file.
Steps how the object is serialized and de-serialized.
Answer for: How did it convert to 51 bytes file?
java.lang.Object
.If you are interested in more in-depth information about Java Serialization please check this link.
Edit : One more good link to read.
This will answer a few frequent questions:
How not to serialize any field in class.
Ans: use transient keyword
When child class is serialized does parent class get serialized?
Ans: No, If a parent is not extending the Serializable interface parents field don't get serialized.
When a parent is serialized does child class get serialized?
Ans: Yes, by default child class also gets serialized.
How to avoid child class from getting serialized?
Ans: a. Override writeObject and readObject method and throw NotSerializableException
.
b. also you can mark all fields transient in child class.