Why must a final variable be initialized before constructor completes?
public class Ex { final int q; }
When I compile this code I get error like this
err:variable q might not have been initialized
It makes sense to initialize the variable at declaration to avoid redundancy. It also makes sense to consider final variables in such a situation. If you know what value a final variable will have at declaration, it makes sense to initialize it outside the constructors.
A blank final variable can be initialized inside an instance-initializer block or inside the constructor. If you have more than one constructor in your class then it must be initialized in all of them, otherwise, a compile-time error will be thrown.
Declaring final variable without initialization If you declare a final variable later on you cannot modify or, assign values to it. Moreover, like instance variables, final variables will not be initialized with default values. Therefore, it is mandatory to initialize final variables once you declare them.
You should always initialize native variables, especially if they are class member variables. Class variables, on the other hand, should have a constructor defined that will initialize its state properly, so you do not always have to initialize them.
The official reason is that it is defined by the Java Language Specification 8.3.1.2:
A blank final instance variable must be definitely assigned at the end of every constructor of the class in which it is declared; otherwise a compile-time error occurs.
A blank final is a final variable whose declaration lacks an initializer (i.e. what you describe).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With