Open In App

Externalizable interface in Java

Externalization serves the purpose of custom Serialization, where we can decide what to store in stream.
Externalizable interface present in java.io, is used for Externalization which extends Serializable interface. It consist of two methods which we have to override to write/read object into/from stream which are- 
 

// to read object from stream
void readExternal(ObjectInput in) 

// to write object into stream
void writeExternal(ObjectOutput out) 

Key differences between Serializable and Externalizable 
 



Below is the example for Externalization-
 





Output: 
 



Default Constructor called
The original car is:
Name: Shubham
Year: 1995
Age: 10
The new car is:
Name: Shubham
Year: 1995
Age: 10

In the example, the class Car has two methods- writeExternal and readExternal. So, when we write “Car” object to OutputStream, writeExternal method is called to persist the data. The same applies to the readExternal method. 
When an Externalizable object is reconstructed, an instance is created first using the public no-argument constructor, then the readExternal method is called. So, it is mandatory to provide a no-argument constructor. 
When an object implements Serializable interface, is serialized or deserialized, no constructor of object is called and hence any initialization which is implemented in constructor can’t be done. 

 

Article Tags :