N00*_*mer -2 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");
}
}
Run Code Online (Sandbox Code Playgroud)
控制台输出:
SYSO within empty braces
SYSO within constructor() method
SYSO within main() method
Run Code Online (Sandbox Code Playgroud)
这里的问题是,为什么在对象实例创建EmptyBraces类期间首先执行空括号内的代码片段(尽管它从未声明为STATIC显式)?
the piece of code within the empty braces被称为实例初始化块.无论何时创建类的实例,它都会在构造函数体之前(以及在执行超类构造函数之后)执行.
| 归档时间: |
|
| 查看次数: |
167 次 |
| 最近记录: |