Skip to content
Advertisement

Make immutable Java object

My goal is to make a Java object immutable. I have a class Student. I coded it in the following way to achieve immutability:

JavaScript

My question is, what is the best way to achieve immutability for the Student class?

Advertisement

Answer

Your class is not immutable strictly speaking, it is only effectively immutable. To make it immutable, you need to use final:

JavaScript

Although the difference might seem subtle, it can make a significant difference in a multi-threaded context. An immutable class is inherently thread-safe, an effectively immutable class is thread safe only if it is safely published.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement