我对Java中的基本内容感到困惑。
public class InitItself1 {
public InitItself1(){}
private InitItself1 me = new InitItself1();
}
当然,我知道在创建上述类的实例时会发生StackOverFlowError。由于变量“ me”的启动,上述类本身将以递归方式启动。
但,
public class InitItself2 {
public InitItself2(){}
private static InitItself2 me = new InitItself2();
}
当然,以上类“ InitItself2”的结果与上一类“ InitItself1”不同。这工作得很好,没有发生错误。据我所知,当加载了静态变量和块的类时,将执行初始化静态变量和执行静态块的操作。
让我感到困惑的是,我认为两个类“ InitItself1”和“ InitItself2”的变量“ me”都是相同的,并且它们都引用了它们所在的类,因此看起来“递归启动”将在启动两个类时发生。
我想念的是什么?请给我一个好的答案。谢谢 :)
在第二种情况下,您不会得到StackOverFlowError。就像您自己说的那样,静态变量是在类加载时启动的,并且由于类仅加载一次,因此静态InitItself2 me
实例仅被实例化一次。使用构造函数创建新对象不需要重新加载该类。
public final class InitItself {
static {
System.out.println("Class is loaded");
}
private static InitItself me = new InitItself();
static {
System.out.println("me is instantiated");
}
public InitItself() {
System.out.println("Constructor called, me=" + me);
}
public static void main(String[] args) {
System.out.println("START");
InitItself i = new InitItself();
System.out.println("FINISH");
}
}
提供以下输出
Class is loaded
Constructor called, me=null
me is instantiated
START
Constructor called, me=oop.InitItself@6ff3c5b5
FINISH
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句