Home  >  Article  >  Java  >  What\'s the Execution Order of Static and Instance Initializer Blocks in Java?

What\'s the Execution Order of Static and Instance Initializer Blocks in Java?

Barbara Streisand
Barbara StreisandOriginal
2024-11-24 08:28:09869browse

What's the Execution Order of Static and Instance Initializer Blocks in Java?

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:

  1. Static initializer blocks of the parent class are executed first.
  2. Static initializer blocks of the direct subclass are executed next.
  3. This order is followed recursively until all subclasses have had their static initializer blocks executed.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn