我不确定为什么会导致堆栈溢出.我知道如果我在没有实例的情况下调用someMethod方法它可以正常工作,但我想知道原因.谢谢
class test { public static void main(String[] args) { test item = new test(); item.someOtherMethod(); } test item2 = new test(); void someOtherMethod() { item2.someMethod(); } void someMethod() { System.out.println("print this"); } }
Cruncher.. 5
test item2 = new test();
这是您班级中的实例变量test
.当你创建一个实例时test
,它将创建一个新实例test
并分配给它item2
.但是test
必须制作一个test
并将其分配给它item2
等等......你得到无限递归,所以你会很快得到任何堆栈的堆栈溢出
test item2 = new test();
这是您班级中的实例变量test
.当你创建一个实例时test
,它将创建一个新实例test
并分配给它item2
.但是test
必须制作一个test
并将其分配给它item2
等等......你得到无限递归,所以你会很快得到任何堆栈的堆栈溢出