In a class, I am declaring a field that does not change from the assignment onwards. This field (or constant, to be precise) is also shared by all instances of the class.
For the two reasons above, I am using the
final
and
static
keywords when declaring the constant.
However, since, I am using both final and static, I need to assign a value at the declaration, because the constant is assigned its value when the class is loaded. Unfortunately, in this case, this cannot be done because that value is not known to the program from the beginning but only when the class is instantiated (because its value is figured out by the program). It must, therefore, be assigned its value within the constructor of the class based on a parameter passed to it.
As previously said, this is illegal in java.
I do not know how to solve the problem. Everything suggests that I should use both static and final, because the field is shared by all instances of the class and does not change from the moment a value is assigned to it.
Moreover, according to Android documentation, usage of the final keyword has the following advantage:
accesses to [a final field] will use a relatively inexpensive "string constant" instruction instead of a field lookup.
Additionally, usage of the static keyword has the advantage that only one field is used for all instances instead of one field per instance.
It is therefore highly important that I be able to use both those keywords for performance reasons.
Summing up: I need to use both final and static but, because the value of the constant is not known at class load-up, I cannot do it. Is there a workaround so that I can still use final and static for my constant?