There are four types of fields of a class and its instances:
- static field
- final static field
- instance field
- final instance field
- static initialization block
- object initializer block
- inline field initializer. This can be a default value or a method call.
- constructor
The code below contains all the concepts mentioned above and the output of the program shows the order of the initialization of each field.
public class OrderOfInitialization {
private static int staticValue; // staticValue will be initialized in the static initialization block.
private final static String finalStaticValue = "final static field must be initialized.";
{
System.out.println("Object initializer block is executed.");
y = 20;
}
private int x = valueFromInitializer();
private int y; // y will be initialized in the initializer block
private int z; // z will be initialized in the constructor.
static {
System.out.println("Static initialization block is executed.");
staticValue = 100;
}
public final int valueFromInitializer() {
System.out.println("valueFromInitializer() is called.");
return 10;
}
public OrderOfInitialization() {
System.out.println("Constructor() is called.");
System.out.println("(uninitialized) z = " + z);
z = 30;
System.out.println("(initialized in constructor) z = " + z);
System.out.println("staticValue = " + staticValue);
System.out.println("finalStaticValue = " + finalStaticValue);
}
public static void main(String[] args) {
OrderOfInitialization instance = new OrderOfInitialization();
}
}
Here is the output of the program:
Static initialization block is executed. Object initializer block is executed. valueFromInitializer() is called. Constructor() is called. (uninitialized) z = 0 (initialized in constructor) z = 30 staticValue = 100 finalStaticValue = final static field must be initialized.
----- END -----
©2019 - 2023 all rights reserved