Home >Java >javaTutorial >Why Does This Java Program Output 'YYXZ' Instead of 'XZYY'?

Why Does This Java Program Output 'YYXZ' Instead of 'XZYY'?

Susan Sarandon
Susan SarandonOriginal
2024-12-16 19:31:11839browse

Why Does This Java Program Output

Understanding Initialization Order in Java Constructors

When constructing an object in Java, it's crucial to comprehend the order of initialization. This question arises: "Can anyone clarify the output of the following program?"

The code:

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();
    }
}

The expected output was "XZYY" under the assumption that constructors are initialized before instance variables. However, the output is actually "YYXZ." This deviation highlights the importance of understanding the actual initialization order.

According to the Java Virtual Machine Specification, the initialization order is as follows:

  1. Static variable initializers and static initialization blocks, in textual order.
  2. The super() call in the constructor, whether explicit or implicit.
  3. Instance variable initializers and instance initialization blocks, in textual order.
  4. Remaining body of constructor after super().

In this case, the static variables and blocks are not involved. The super() call occurs implicitly in the constructor of class Z, so it is not visible in the code. Therefore, the initialization order is:

  1. Instance variable initializers of class X (b)
  2. Instance variable initializers of class Y (y)
  3. Constructor body of class X (prints "X")
  4. Constructor body of class Z (prints "Z")

This explains the output "YYXZ."

The above is the detailed content of Why Does This Java Program Output 'YYXZ' Instead of 'XZYY'?. 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