Why declare a reference to an instance of the final class as final?

What is the value of the second line:

public final class A {} final A obj1=new A(); 

If A is already immutable, why might you want to make obj1 final? (just to make it stick to a unique memory reference?).

+6
source share
2 answers

final in the first line means that the object is closed for expansion ... i.e. you cannot subclass it.

final in the second line means you cannot reassign the variable.

+15
source

Firstly, A not immutable; you simply declare it final .

Then the final variables cannot be changed. If obj1 is a field, this provides variability (as opposed to final class ).

If this is a local variable, this means that you can safely use it in anonymous classes (otherwise the compiler cannot be sure that it will not receive changes sometimes before / at the time the class is anonymous)

+2
source

Source: https://habr.com/ru/post/892162/


All Articles