Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immutability in Java

Tags:

java

If my class is going to be an immutable one it has to be final and without any method that modifies its state and all properties must be private. But why should it have properties declared as final (for example, private final int a)?

Edit

Will the class still be an immutable one if it has a reference to objects that are not immutable?

like image 982
maks Avatar asked Dec 10 '22 08:12

maks


2 Answers

If you mark a private member variable as final, you enlist the compiler and runtime engine to ensure that its value can never be modified, neither by the class itself or its subclasses.

like image 131
duffymo Avatar answered Dec 11 '22 22:12

duffymo


A final class is one that cannot be subclassed. The final keyword on a class definition does not necessarily make the class immutable. So your class does not have to be final for instances of it to be immutable (your question implies that you are making the class final, note that final can be used to modify more than just classes). However, if you make a class final that class cannot be subclassed, so you are guaranteed that no mutable subclasses can be created.

Immutability simply means that no values on the class can be changed. So private fields, no non-private setters should do it. One common issu is if your class has a Collection, you have to return some sort of unmodifiable collection, else the values in the collection can be changed, even though noone could change the reference to the collection. This answers the second part of your question. If declare a final myCollection on your class, you can't change the reference to myCollection, but you can still modify the collection outside of the class, if you have a getter (which is fine) and don't return an unmodifiable collection. See http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#unmodifiableCollection(java.util.Collection)

With respect to immutability, keep in mind that the goal is to make it impossible to change instances of a class, once the values are initially set. Using the final keyword can help, but is not by itself sufficient to have an immutable definition.

like image 34
hvgotcodes Avatar answered Dec 11 '22 22:12

hvgotcodes