Home > Java > javaTutorial > What's the Correct Execution Order of Instance Variable Initialization and Constructor Execution in Java?

What's the Correct Execution Order of Instance Variable Initialization and Constructor Execution in Java?

Linda Hamilton
Release: 2024-12-29 05:47:10
Original
611 people have browsed it

What's the Correct Execution Order of Instance Variable Initialization and Constructor Execution in Java?

Instance Variable Initialization vs. Constructor Execution in Java

One common misconception about Java object initialization is the order in which fields and constructors are executed. Let's clarify this concept with an example.

In the given code snippet:

class X {
    Y b = new Y();

    X() {
        System.out.print("X");
    }
}

class Y {
    Y() {
        System.out.print("Y");
    }
}

public class Z extends X {
    Y y = new Y();

    Z() {
        System.out.print("Z");
    }

    public static void main(String[] args) {
        new Z();
    }
}
Copy after login

Contrary to the assumption that fields are initialized before constructors, the output of this program is "YZX". To understand why, we need to delve into the Java initialization process.

Initialization Order:

Java initializes classes in a specific sequence:

  1. Static Members: Static variables and initializers in textual order.
  2. Constructor Invocation: Super constructor call, either explicit or implicit.
  3. Instance Variable and Initializer Blocks: Fields and instance initialization blocks in textual order.
  4. Constructor Body: Remaining code in the constructor after the super() call.

In the example above, the sequence of events is:

  • Y's constructor is called (Y).
  • Z's constructor calls X's constructor (YZ).
  • X's constructor is called (XYZ).
  • X's instance variable b is initialized (YZXb).
  • Z's instance variable y is initialized (YZXby).

Therefore, the correct order of execution is "YZX". This highlights the importance of understanding the Java initialization order to avoid unexpected behavior in object construction.

The above is the detailed content of What's the Correct Execution Order of Instance Variable Initialization and Constructor Execution 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