根据
JLS:
A class or interface type T will be initialized immediately before the
first occurrence of any one of the following:
T is a class and an instance of T is created.
也说,
Initialization of a class consists of executing its static
initializers and the initializers for static fields (class variables)
declared in the class
我从中推断出两点
>类初始化包括执行其静态初始化器
>如果类实例化,则会发生类初始化。
现在,
我假设当我自己创建一个Test(测试自己的)静态初始化器的对象时,它应该给我一个堆栈溢出,因为它应该重复调用自己,因为根据上述两点,类的实例化应该初始化类,初始化块具有类的实例化。当我在自己的构造函数或其自己的实例初始化器中实例化类时,会发生堆栈溢出。
例如,
public class Test {
static{
System.out.println("static test");
new Test();
}
{
//new Test(); // This will give a stack overflow
System.out.println("intializer");
}
public Test(){
//new Test(); // This will give a stack overflow
System.out.println("constructor");
}
public static void main(String[] args) {
}
}
然而结果却有所不同。
结果:
static test
intializer
constructor
要么我对这个课程的初始化感到太困惑,要是我在这里遗漏了一些非常明显的东西,并且感谢您的帮助,我们深表歉意。