Manjul
Manjul

Reputation: 189

why we have Externalizable when we can override writeObject and readObject in java

As we can override the default serialization process by overriding writeObject() and readObject() , then What is the need of Externalizable interface?

Upvotes: 19

Views: 1902

Answers (3)

amarnath harish
amarnath harish

Reputation: 971

this question has some reasonable answer here

"The CPU cost of serializing Java objects can be significant. This expense, in turn, affects JMS Object messages. You can offset this cost, to some extent, by having application objects implement java.io.Externalizable, but there still will be significant overhead in marshalling the class descriptor. To avoid the cost of having to write the class descriptors of additional objects embedded in an Object message, have these objects implement Externalizable, and call readExternal and writeExternal on them directly. For example, call obj.writeExternal(stream) rather than stream.writeObject(obj). Using Bytes and Stream messages is generally a preferred practice."

this is The best rationale I've been able to find (in Oracle documentation) is in the WebLogic JMS Best Practice document:

Upvotes: 4

snehal
snehal

Reputation: 1846

Serializable interface is implement for getting an automatic serialization functionality but if you like to provide your own serialization logic(custom logic) you would go for Externalizable interfaces. Externalizable interface contains two methods which you have to implement that is readExternal() and writeExternal().

If you implement Serializable interface everything including the state of all the Base Classes (Super Classes) are taken care by the default(automatic) Serialization process .

Upvotes: -1

sanbhat
sanbhat

Reputation: 17622

Class implementing Serializable may or may not wish to change the format in which the instance of that class, written into the stream.

But, Class implementing Externalizable must implement writeExternal and readExternal methods, and its the class's responsibility to write and restore the data to/from the stream.

Upvotes: 5

Related Questions