Reputation: 19037
A final field has to be initialized only once in Java by convention. No other initializations are permitted. The following program demonstrates the use of final and final static fields within a class.
package main;
import java.util.ArrayList;
import java.util.List;
final public class Main
{
private final static int a=10;
private final List<String> list;
public Main()
{
list=new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
}
private void show()
{
for(String l:list)
{
System.out.println(l);
}
}
public static void main(String[] args)
{
new Main().show();
}
}
In the above code, the final field list
of type ArrayList
is being initialized within the constructor itself. The same thing is however not applicable to the final static field a
. An attempt to initialize a
within the constructor body causes a compile-time error indicating that "can not assign a value to a final variable a". Why is the same thing not applicable to the final static field list which is being allowed to initialize within the constructor?
Upvotes: 3
Views: 307
Reputation: 5563
If you declare final alone its an constant for each instance and you can initialize it in the constructor as you did. But If you declare final static, all the instances will share the same variable. So you can't initialize in the constructor, because you trying to change the value whenever the instance is created.
Upvotes: 2
Reputation: 12548
You already initialized a with its definition, because you set it to 10. Afterwards you cannot modify it in the constructor.
Running your constructor twice will cause problems for the list as well.
Upvotes: 0
Reputation: 1503090
The same thing is applicable to final static fields - but in the closest static equivalent to a constructor, namely a static initializer:
private final static int x;
static {
x = 10;
}
(Arguably that's closer to an instance initializer than to a constructor, but it's the closest you get for static. It's not like you can specify arguments or anything.)
The constructor is run on each instantiation of the class - if that were able to change a final static field, it wouldn't be very final, would it? Remember that there's just one "copy" of the static variable associated with the type, rather than one associated with each instance of the type as with instance variables.
Upvotes: 6