为什么在 class 的构造函数之前先执行空括号内的代码?
Why is the code within empty braces getting executed first even before the constructor of the class?
虽然这是一个小问题,但想了解这种奇怪的行为!以下是正在讨论的代码和代码的行为(通过控制台输出)。
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
class 的对象实例创建期间首先执行空括号内的代码段(尽管它从未声明为 STATIC
明确地)?
the piece of code within the empty braces
被称为实例初始化块。每当创建 class 的实例时,它都会在构造函数主体之前(以及在执行超级 class 构造函数之后)执行。
这是因为在执行 EmptyBracesWithinClass 的打印方法之前,您通过实例化它来调用 EmptyBraces。所以静态初始化程序块 运行 首先构造函数将 运行.
虽然这是一个小问题,但想了解这种奇怪的行为!以下是正在讨论的代码和代码的行为(通过控制台输出)。
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
class 的对象实例创建期间首先执行空括号内的代码段(尽管它从未声明为 STATIC
明确地)?
the piece of code within the empty braces
被称为实例初始化块。每当创建 class 的实例时,它都会在构造函数主体之前(以及在执行超级 class 构造函数之后)执行。
这是因为在执行 EmptyBracesWithinClass 的打印方法之前,您通过实例化它来调用 EmptyBraces。所以静态初始化程序块 运行 首先构造函数将 运行.