I was asked this question in an interview. The interviewer wanted to know how to make an object immutable. and then he asked what if I serialise this object - will it break immu
As others have said, one could make the argument that serialization results in a brand new object, which is then immutable, so no, serialization doesn't break it, but I think there's a bigger picture to immutability we have to consider before answering that question.
I think the real answer depends completely on the class being serialized, and the level of immutability required, but since the interviewer failed to give us source code, I will come up with my own. I'd also like to point out that, as soon as people start talking about immutability, they start throwing around the final
keyword - yes, that makes a reference immutable, but it's not the only way to achieve immutability. Okay, let's look at some code:
public class MyImmutableClass implements Serializable{
private double value;
public MyImmutableClass(double v){
value = v;
}
public double getValue(){ return value; }
}
Is this class mutable because I implemented Serializable
? Is it mutable because I didn't use the final
keyword? No way - it's immutable in every practical sense of the word, because I'm not going to modify the source code (even if you ask me to nicely), but more importantly, it's immutable because no outside class can change the value of value
, short of using Reflection to make it public and then modifying it. By that token, I suppose you could run some intermediary hex editor and manually modify the value in RAM too, but that doesn't make it any more mutable than it was before. Extending classes can't modify it either. Sure, you can extend it and then override getValue()
to return something different, but doing so will not have changed the underlying value
.
I know this might rub a lot of people the wrong way, but it's my opinion that immutability is often purely semantic - e.g. is it immutable to someone calling your code from an outside class, or is it immutable from someone using BusPirate on your motherboard? There are VERY good reasons to use final
to help ensure immutability, but I think it's importance is vastly overstated in more than a few arguments. Just because the JVM is allowed to do some magic under the hood to ensure Serialization works doesn't mean the level of immutability your application requires is somehow broken.