My understanding is that you cannot reference a variable before it has been declared, and that all code (including instance initializers) that is within the body of a class, but outside of any method, is executed in order before constructor when the object is created (the exception being static
variables and initializer blocks, which are run in order at the beginning of the program, to initialize the entire class). Why, then, does the following code compile (and run!):
public class WhyIsThisOk {
{ a = 5; } // why is this ok???
int a = 10;
public WhyIsThisOk() {
}
public static void main(String[] args) {
WhyIsThisOk why = new WhyIsThisOk();
System.out.println(why.a); // 10
}
}
Instance Initializer block is used to initialize the instance data member. It run each time when object of the class is created. The initialization of the instance variable can be done directly but there can be performed extra operations while initializing the instance variable in the instance initializer block.
Instance Initialization blocks are executed whenever the class is initialized and before constructors are invoked. They are typically placed above the constructors within braces.
Static blocks can be used to initialize static variables or to call a static method. However, an instance block is executed every time an instance of the class is created, and it can be used to initialize the instance data members.
Instance Initializer Block in Java: It is declared within the curly braces of the class but outside of any method. The value of an instance variable can be changed by any method in the class, but it is not accessible from outside the class. Instance variables are usually initialised when the object is created.
From docs:
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
The above statement is slightly misleading, because if we follow the explanation of the above doc we can rewrite the original code like this:
public class WrongVersionOfWhyIsThisOk {
int a = 10;
public WhyIsThisOk (){
a = 5;
}
public static void main(String[] args){
WrongVersionOfWhyIsThisOk why = new WrongVersionOfWhyIsThisOk ();
System.out.println(why.a);
}
}
But running WrongVersionOfWhyIsThisOk
will produce 5 instead of 10 that original code produces.
But in reality it is both the initializer block and variable assignment are copied into constructor:
public class RightVersionOfWhyIsThisOk {
int a;
public RightVersionOfWhyIsThisOk (){
a = 5;
a = 10;
}
public static void main(String[] args){
RightVersionOfWhyIsThisOk why = new RightVersionOfWhyIsThisOk ();
System.out.println(why.a);
}
}
Update:
Here is the doc describing in detail the initialization order and constructor invocation:
4) Execute the instance initializers and instance variable initializers for this class, assigning the values of instance variable initializers to the corresponding instance variables, in the left-to-right order in which they appear textually in the source code for the class. If execution of any of these initializers results in an exception, then no further initializers are processed and this procedure completes abruptly with that same exception. Otherwise, continue with step 5.
5) Execute the rest of the body of this constructor. If that execution completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, this procedure completes normally.
From docs:
8.3.2.3. Restrictions on the use of Fields during Initialization
The declaration of a member needs to appear textually before it is used only if the member is an instance (respectively static) field of a class or interface C and all of the following conditions hold:
The usage occurs in an instance (respectively static) variable initializer of C or in an instance (respectively static) initializer
of C.The usage is not on the left hand side of an assignment.
The usage is via a simple name.
C is the innermost class or interface enclosing the usage.
It is a compile-time error if any of the four requirements above are not met
In this case, the usage is on the left hand side of the assignment, so it is not a compile-time error.
The instance initialization blocs are called at the instance creation time.so it is normal that After the creation of the why object, it Works.
The order of initialisation is: 1) static bloc 2)constructor 3)instance blocs on order of appearance
The contents of initializer block are executed whenever any constructor is invoked (before the constructor’s contents).
So you can provide reference to any variables as they will not be used unless a constructor is invoked aka. object is created.
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