In immutable objects making the variables private will restrict the access from external world. What is the need for making the variables final ? Is the reason is only to make it readable ? that if the variables are final it means the object is immutable ? Is there any theoretical reason behind it ?
-
Helps prevent accidents, and there are some extra thread safety guarantees. – user2357112 Jul 22 '17 at 21:03
-
Read here: https://stackoverflow.com/questions/16061030/must-all-properties-of-an-immutable-object-be-final?rq=1 – Ivan Pronin Jul 22 '17 at 21:09
2 Answers
You do not mark variable as final, but a reference to a variable. It does not guarantee immutability at all. It merely guarantees that once assigned final reference can't be reassigned + gives you thread safety guarantee.
Consider an example like this:
class A {
private int someVariable = 5;
public void setSomeVariable(int someVariable) {
this.someVariable = someVariable;
}
class B {
private final A a;
public B(A a) {
this.a = a;
}
}
public class C {
public static void main(String[] args) {
A someA = new A();
B someB = new B(someA);
//field a in B is final but I can do this:
someA.setSomeVariable(6); // by having a reference to someA I have modified someB though it is a final field
}

- 1,240
- 14
- 32
You seem to have a few misconceptions in your understanding. Let's go over them one by one.
if the variables are final it means the object is immutable
This is not right. Immutability and marking something as final
are completely different concepts.
Immutability makes an object's properties (fields) unchangeable once the object is created. final
variables on the other hand, is something that you cannot change the value of after the first assignment.
Let's consider this immutable object's class:
class MyClass {
private int myField;
public int getMyField() { return myField; }
public MyClass(int myField) { this.myField = myField; }
}
As you can see, myField
cannot change upon initialisation. It cannot be changed in any part of the code except the constructor. Let's create a variable of this:
MyClass obj = new MyClass(10);
As we know, obj.myField
cannot be changed anymore at this point, but can obj
be changed? Yes it can e.g.
obj = null;
You can declare it final
to make obj
unchangeable:
final MyClass obj = null;
obj = new MyClass(10); // error!
Now that you see the difference between final and immutability, let's move on to the benefits of both.
Immutability and final
have pretty much the same benefits. They both ensure that values that should stay the same will not be accidentally changed. It is more to "avoid mistakes" than to "improve readability".

- 213,210
- 22
- 193
- 313