patternjavaCritical
How does the "final" keyword in Java work? (I can still modify an object.)
Viewed 0 times
stillobjecthowjavamodifythedoescanfinalkeyword
Problem
In Java we use
But I see that you can change the value in the constructor / methods of the class. Again, if the variable is
Here is the code:
Above code works fine and no errors.
Now change the variable as
Now it is a compilation error. How does this
final keyword with variables to specify its values are not to be changed.But I see that you can change the value in the constructor / methods of the class. Again, if the variable is
static then it is a compilation error.Here is the code:
import java.util.ArrayList;
import java.util.List;
class Test {
private final List foo;
public Test()
{
foo = new ArrayList();
foo.add("foo"); // Modification-1
}
public static void main(String[] args)
{
Test t = new Test();
t.foo.add("bar"); // Modification-2
System.out.println("print - " + t.foo);
}
}Above code works fine and no errors.
Now change the variable as
static:private static final List foo;Now it is a compilation error. How does this
final really work?Solution
You are always allowed to initialize a
Note that calling methods on an object stored in a
Java has no concept of object immutability; this is achieved by carefully designing the object, and is a far-from-trivial endeavor.
final variable. The compiler makes sure that you can do it only once. Note that calling methods on an object stored in a
final variable has nothing to do with the semantics of final. In other words: final is only about the reference itself, and not about the contents of the referenced object.Java has no concept of object immutability; this is achieved by carefully designing the object, and is a far-from-trivial endeavor.
Context
Stack Overflow Q#15655012, score: 615
Revisions (0)
No revisions yet.