In Java we use
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?
No comments:
Post a Comment