Initialization Sequence of Static and Instance Blocks in Java
When working with multiple classes in Java, understanding the order of execution for static and instance initializer blocks becomes crucial. While it's known that within a class, these blocks run in order of appearance, there remains uncertainty regarding their behavior across classes.
To demonstrate this behavior, consider the following code:
package pkg; public class LoadTest { public static void main(String[] args) { System.out.println("START"); new Child(); System.out.println("END"); } } class Parent extends Grandparent { // Instance init block { System.out.println("instance - parent"); } // Constructor public Parent() { System.out.println("constructor - parent"); } // Static init block static { System.out.println("static - parent"); } } class Grandparent { // Static init block static { System.out.println("static - grandparent"); } // Instance init block { System.out.println("instance - grandparent"); } // Constructor public Grandparent() { System.out.println("constructor - grandparent"); } } class Child extends Parent { // Constructor public Child() { System.out.println("constructor - child"); } // Static init block static { System.out.println("static - child"); } // Instance init block { System.out.println("instance - child"); } }
Expectedly, the output of this code aligns with the assumption that static blocks execute before instance blocks:
START static - grandparent static - parent static - child instance - grandparent constructor - grandparent instance - parent constructor - parent instance - child constructor - child END
However, this observation alone does not clarify the initialization order between parents and children classes. To further explore this aspect, consider adding the following unused class to the code:
class IAmAClassThatIsNeverUsed { // Constructor public IAmAClassThatIsNeverUsed() { System.out.println("constructor - IAACTINU"); } // Instance init block { System.out.println("instance - IAACTINU"); } // Static init block static { System.out.println("static - IAACTINU"); } }
Remarkably, the modified code still produces the same output as the original code. This implies that the static and instance initializer blocks execute in the following sequence:
This behavior aligns with the Java Language Specification (JLS), which provides detailed explanations in sections 12.4 and 12.5.
The above is the detailed content of What\'s the Initialization Order of Static and Instance Blocks in Java Inheritance?. For more information, please follow other related articles on the PHP Chinese website!