Execution Order of Static and Instance Initializer Blocks in Java
When working with Java classes, it's essential to understand the order in which static and instance initializer blocks are executed. These blocks perform vital operations like assigning initial values and initializing class and object members.
Instance Initializer Blocks
Instance initializer blocks, enclosed in curly braces { }, are executed every time an instance of a class is created. They are executed in the order they appear in the code within the class. This behavior is consistent across all classes.
Static Initializer Blocks
Static initializer blocks, also enclosed in curly braces { } and preceded by the static keyword, are executed when the class is loaded. They are not associated with any specific instance and are executed only once, regardless of the number of instances created.
Specific Execution Order
The Java Language Specification (JLS) defines a specific order for the execution of static initializer blocks:
Example
Consider the following code example:
class Grandparent { static { System.out.println("Static - Grandparent"); } } class Parent extends Grandparent { static { System.out.println("Static - Parent"); } } class Child extends Parent { static { System.out.println("Static - Child"); } }
When the main method is executed, the following output is generated:
Static - Grandparent Static - Parent Static - Child
This demonstrates that the static initializer blocks are executed in the order parent -> subclass.
Exceptions
There is one notable exception to this rule. If the parent class defines a class that is never referenced, its static initializer block will not be executed. This is because the class loader only initializes classes that are explicitly required.
The above is the detailed content of What\'s the Execution Order of Static and Instance Initializer Blocks in Java?. For more information, please follow other related articles on the PHP Chinese website!