Why must a final variable be initialized before constructor completes?
public class Ex
{
final int q;
}
When I compile this code I get er
The final
keyword applied to a field has one of two effects:
final HashMap<String,String> a
, you will only be able to set it once, and you won't be able to do this.a=new HashMap<String,String>();
again, but nothing keeps you from doing this.a.put("a","b")
,s since that doesn't modify the reference, only the content of the object.Final
modifier does not allow to change your variable value. So you need to assign a value to it at some place and constructor is the place you have to do this in this case.
The final
modifier prevents your from changeing the variables value, hence you have to initialize it where you declare it.
If an instance variable is declared with final keyword, it means it can not be modified later, which makes it a constant. That is why we have to initialize the variable with final keyword.Initialization must be done explicitly because JVM doesnt provide default value to final instance variable.Final instance variable must be initialized either at the time of declaration like:
class Test{
final int num = 10;
}
or it must be declared inside an instance block like:
class Test{
final int x;
{
x=10;
}
}
or it must be declared BEFORE constructor COMPLETION like:
class Test{
final int x;
Test(){
x=10;
}
}
Keep in mind that we can initialize it inside a consructor block because initialization must be done before constructor completion.
The language specification contains specific guarantees about the properties of final variables and fields, and one of them is that a properly constructed object (i.e. one whose constructor finished successfully) must have all its final instance fields initialized and visible to all threads. Thus, the compiler analyzes code paths and requires you to initialize those fields.
The value of a final
variable can only be set once. The constructor is the only place in the code for a class that you can guarantee this will hold true; the constructor is only ever called once for an object but other methods can be called any number of times.