I read this question about immutable objects and was left with a question regarding immutable objects and final field:
Why do we need instance variable in immutab
By marking all of a class' fields final
, you make it clear that you intend your class to be immutable.
Suppose you have the following class:
public class Immutable {
private int value;
public Immutable (int value) {
this.value = value;
}
public int getValue () {
return value;
}
}
There is no setter method, so one could easily assume that this class is immutable. Which it is, for now. But eventually your class will be modified by some other programmer, and this programmer might add some methods to your class:
public class Immutable {
private int value;
public Immutable (int value) {
this.value = value;
}
public int getValue () {
return value;
}
public void doSomething () {
value++;
}
}
It is quite easy to inadvertently add a method that modifies the state of your object if the fields are not final
. By marking them final
, this other programmer will get a compile error when he tries to modify the field, and will have to ask himself why is this field final
, and does his modification breaks the contract of this class.
One could argue that the Javadoc should be used to document that said class is immutable, but quite frankly, not everyone reads the Javadoc. Making the code speak for itself is better in my opinion.