The Depths of Immutable Class Design — 1
Have you ever wondered why we need to mark the class as
final, and why no setters, why
private final fields while designing Immutable classes in Java?
We all know the rules of creating immutable classes. If you aren’t aware of those rules there are tons of articles on Medium already written by other authors. But when it comes to interviews we often fail to give the proper example for each rule. This two article series exactly addresses that. My motive for this article is to give you the one-stop in-depth guide to creating immutable classes and cover the most trickier interview question about marking the fields
final. In this article, we will understand why we need to mark the class as
We all know what immutable classes are. A conservative definition of Immutability is that the State of the object doesn’t ever get changed once it is created. By State what we mean is the Properties (or fields in technical terms) of the object. So the class has to be designed in such a way that, its objects, once published in the heap, never allow their state to be mutated. For this, there are different rules. And in this two article series, we are gonna look at each rule one by one with a perfect example. Let us look at all the rules once.
Rules for designing Immutable Classes
- Prevent the class from Subclassing
- Don’t provide setter methods.
- Take care of Constructors Taking External References
- Take care of Getters returning a reference to non-immutable objects.
- Make all the fields final and private.
1. Why Prevent the class from Subclassing
If we allow a class to be subclassed, there may be malicious subclasses that compromise the immutable behavior by behaving as if the object’s state has changed. Note that we are choosing our words carefully here. We did not say that the subclasses change the state. Of course, they cannot change it because the fields are also marked as final. We are saying the subclasses behave as if they have changed the object’s state. What does this mean? Let us…