为什么我可以在实例初始化块中调用实例方法?

问题描述 投票:0回答:1

实例初始化块在构造函数之前调用,但 this 已在其中可用。因此我们可以调用任何公共或私有方法。但为什么?只有构造函数才能保证 this

的实例创建和可用性
public class Test {

    {
        this.privatePrint();
        this.publicPrint();
    }

    public Test() {
        System.out.print(" Constructor ");
    }

    public void publicPrint() {
        System.out.print(" public ");
    }

    public void privatePrint() {
        System.out.print(" private ");
    }

    public static void main(String[] args) {
        new Test();
    }

}

输出是

private  public  Constructor

我在jdk 11和17上测试过

我对对象初始化方法的顺序行为感到惊讶

java constructor initialization
1个回答
0
投票

Java 语言规范(12.5 创建新类实例)具有确切的详细信息。

基本上,Java 编译器为您的类创建与以下类相同的字节码(其中显式编写对超级构造函数和实例初始值设定项的调用):

public class Test {

    public Test() {
        super();  // Point 3: call the super constructor
        {  // Point 4: execute instance initializers and instance variable initializers
            this.privatePrint();
            this.publicPrint();
        }
        // Point 5: Execute the rest of the body of this constructor
        System.out.print(" Constructor ");
    }

    public void publicPrint() {
        System.out.print(" public ");
    }

    public void privatePrint() {
        System.out.print(" private ");
    }

    public static void main(String[] args) {
        new Test();
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.