Home > Java > javaTutorial > What's the Actual Order of Field Initialization and Constructor Execution in Java?

What's the Actual Order of Field Initialization and Constructor Execution in Java?

Mary-Kate Olsen
Release: 2024-12-11 15:00:19
Original
527 people have browsed it

What's the Actual Order of Field Initialization and Constructor Execution in Java?

Field Initialization in Java Constructors

In Java, the execution order of field initialization and constructor code has been a topic of confusion. The provided code demonstrates this behavior:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

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

One might expect the output to be "XZYY" based on the assumption that constructors are initialized before instance variables. However, the actual output is "YYXZ":

  • Y(): Constructor of class Y is called.
  • new Y(): Instance variable 'b' in class X is initialized by creating a new instance of 'Y'.
  • X(): Constructor of class X is called.
  • new Y(): Instance variable 'y' in class Z is initialized by creating a new instance of 'Y'.
  • Z(): Constructor of class Z is called.

This output contradicts the expected order because field initialization (e.g., 'b' and 'y') occurs before the execution of constructor bodies (e.g., 'X()' and 'Z()').

The Java Virtual Machine Specification (JVM Spec) clarifies the order of initialization as follows:

  1. Static variable initializers and static initialization blocks are executed.
  2. The super() call in the constructor, if present.
  3. Instance variable initializers and instance initialization blocks are executed in textual order.
  4. Remaining body of the constructor, including any code after super().

Therefore, in the provided code, the instance variables 'b' and 'y' are initialized before the constructor bodies of 'X' and 'Z' are executed, resulting in the output "YYXZ".

The above is the detailed content of What's the Actual Order of Field 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