Immutable classes in Java

Hobbit country: Isengard Hobbit city: Saruman tower Hobbit stuff: []So, it goes with another step to be done:5.

performing cloning of the returned non-primitive mutable object in getter methodsNow the Hack output is:Hobbit country: Hobitton Hobbit city: Shire Hobbit stuff: [Sword, Ring of Power]Immutability has been hacked!Hobbit country: Hobitton Hobbit city: Shire Hobbit stuff: [Sword, Ring of Power]There is one more optional step to be done, but if all other prerequisites are met, it is not necessary.

Anyway, let’s mentioned it:6.

marking all class fields as final (optional)And that’s it, we are done — our Hobbit class is immutable now.

Let’s summarize out steps:removing setters;adding all args constructor;marking the class as final to protect it from being extended;initializing all non-primitive mutable fields via constructor by performing a deep copy;performing cloning of the returned non-primitive mutable object in getter methods;marking all class fields as final (optional step).

Of course, there are other ways to make class immutable (for example, using Builder pattern), but it is out of the scope of the current story.

Have fun!.

. More details

Leave a Reply