When I have an immutable parent class A that is NOT final, and another class B extends it(B is mutable), is there any way the immutability of A can be affected because of serialization?
I wrote a small program to serialize an object, changed its state in the program, and then de-serialized it. I got the object back in the form in which it was serialized. So I am wondering is there any way I can alter A’s immutability by serializing it?
It depends on exactly what you are asking. If you just want to get a different value back than what you put in, then yes, you can do that through serialization. The serialized data is completely detached from the instance of
Athat exists in memory. When Java reconstructs an object from the serialized data, it doesn’t know or care anything about the original instance ofAthat was used to create that data. It is simply constructing a data-structure in memory based off of the blueprint provided in the serialized information.So if you want to modify what you get back when you reconstruct
A, you can do so by manually modifying the binary serialized data. Doing so will require a good understanding of Java’s serialization format, but it can certainly be done.Though if you are asking if there is any way to modify the original instance of
Athrough serialization (as in, to somehow get the same object to change in value, without constructing a new instance via deserialization), then the answer is no, you cannot. Serialization simply creates a snapshot of the object’s current state. Deserialization creates a new object instance that is completely detached from the source instance. So while you might manually change the value, the new object with the new value will still be immutable once it has been deserialized.And if you are asking if there a way to serialize an instance of immutable class
Aand then deserialize the data as something that identifies as an instance of classAbut happens to be mutable then the answer is also no. The serialized data specifies what class of object is being represented, but the class definition itself is not serialized. So you could change the specified class such that you serialize an instance ofAand then deserialize an instance of mutable classB, but that’s not the same as getting back a mutable instance ofA.