为什么即使在类的构造函数之前,空括号中的代码也会先执行?

时间:2016-07-13 11:39:53

标签: java inner-classes

虽然这是一个很小的问题,但想要了解这种奇怪的行为!以下是代码和正在讨论的代码的行为(通过控制台输出)。

public class EmptyBracesWithinClass {
    public static void main(String[] args) {
        EmptyBraces eb = new EmptyBraces();
        System.out.println("SYSO within main() method");
    }
}

class EmptyBraces {
    {
        System.out.println("SYSO within empty braces");
    }

    public EmptyBraces() {
        System.out.println("SYSO within constructor() method");
    }
}

控制台输出:

SYSO within empty braces
SYSO within constructor() method
SYSO within main() method

这里的问题是,为什么在EmptyBraces类的对象实例创建期间首先执行空括号内的代码片段(尽管它从未明确地声明为STATIC)?

2 个答案:

答案 0 :(得分:6)

the piece of code within the empty braces被称为实例初始化程序块。无论何时创建类的实例,它都会在构造函数体之前(以及在执行超类构造函数之后)执行。

答案 1 :(得分:1)

这是因为在打印方法优于EmptyBracesWithinClass之前,您通过实例化它来调用EmptyBraces。所以静态初始化程序块首先运行然后构造函数将运行。