Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why must a final variable be initialized before constructor completes?

Tags:

java

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

like image 281
saravanan Avatar asked Jul 05 '12 13:07

saravanan


People also ask

Why do we initialize variable in constructor?

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.

Can final variable be initialized in a constructor?

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.

Is final variable must be initialized?

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.

Do you have to initialize all variables in constructor?

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.


1 Answers

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).

like image 89
assylias Avatar answered Sep 20 '22 21:09

assylias