In Java, we use the final keyword with variables to indicate that their values should not be modified. But, I see that you may edit the value in the constructor / methods. If the variable is static, this is another compilation fault.
The code is as follows:
The code above is error-free.
Now make the variable static:
It is now a compilation error. How does this final work in practise?
The code is as follows:
Code:
import java.util.ArrayList;
import java.util.List;
class Test {
private final List foo;
public Test()
{
foo = new ArrayList();
foo.add("foo"); // Modification-2
}
public static void main(String[] args)
{
Test t = new Test();
t.foo.add("bar"); // Modification-3
System.out.println("print - " + t.foo);
}
}
The code above is error-free.
Now make the variable static:
Code:
private static final List foo;
It is now a compilation error. How does this final work in practise?