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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With