Open In App

Externalizable interface in Java

Improve
Improve
Like Article
Like
Save
Share
Report

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 
 

  • Implementation : Unlike Serializable interface which will serialize the variables in object with just by implementing interface, here we have to explicitly mention what fields or variables you want to serialize.
  • Methods : Serializable is marker interface without any methods. Externalizable interface contains two methods: writeExternal() and readExternal().
  • Process: Default Serialization process will take place for classes implementing Serializable interface. Programmer defined Serialization process for classes implementing Externalizable interface.
  • Backward Compatibility and Control: If you have to support multiple versions, you can have full control with Externalizable interface. You can support different versions of your object. If you implement Externalizable, it’s your responsibility to serialize super class.
  • public No-arg constructor: Serializable uses reflection to construct object and does not require no arg constructor. But Externalizable requires public no-arg constructor.

Below is the example for Externalization-
 

Java





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. 

 


Last Updated : 11 Jan, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads