The Depths of Immutable Class Design — 1

Beware of Getters and Mark the class as “final”

KRISHNA KISHORE V
7 min readJun 8, 2022
Fig1.1 Code Snippet showing the caution for designing the immutable classes

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 final.

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.

--

--

KRISHNA KISHORE V

Full Stack Tech Lead | Software Consultant | Technical Content Writer