简体   繁体   中英

Is it only for readability that the variables in immutable object defined as final?

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 ?

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



 }

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 eg

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM