Home > Java > javaTutorial > What\'s the Initialization Order of Static and Instance Blocks in Java?

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

Mary-Kate Olsen
Release: 2024-11-25 06:52:18
Original
199 people have browsed it

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

Understanding Initialization Order of Static and Instance Blocks in Java

In Java, initialization blocks play a crucial role in initializing fields before they are used within a program. These blocks can be static or instance-specific, and their execution follows a well-defined order.

Static Initializer Blocks

Static initializer blocks are executed when a class is first loaded by the Java Virtual Machine (JVM). Their execution order is determined by the order in which classes are encountered during the loading process. Specifically:

  • A class will be initialized immediately before any of the following events occur:

    • An instance of the class is created.
    • A static method declared by the class is invoked.
    • A static field declared by the class is assigned a value.

Instance Initializer Blocks

Instance initializer blocks are executed every time an instance of a class is created. Their execution order follows a specific pattern:

  • For each superclass, its static initializer blocks and instance initializer blocks are executed in order.
  • The static initializer blocks of the current class are executed.
  • The instance initializer blocks of the current class are executed.
  • The constructor of the current class is executed.

Sample Code Analysis

In the provided code sample, the output demonstrates the following order of initialization:

  1. Static initializer block of Grandparent
  2. Static initializer block of Parent
  3. Static initializer block of Child

This confirms the principle that static initializer blocks are executed in the order in which their classes are encountered during loading.

Parent-Child Initialization Relationship

While the code sample suggests that parent blocks run before children's, this is not strictly true. The order of initialization for parent and child classes is determined by the class loading order. It is not guaranteed that parent blocks will always run before children's.

The above is the detailed content of What\'s the Initialization Order of Static and Instance Blocks in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template