谁能告诉我为什么会这样?任务是添加最小静态关键字以使此代码有效。使用method1和method2的静态我可以理解,但为什么要将它添加到int step?
/* Minimum number of static keywords
Add the minimum number of static keywords to make the code compile and the program to successfully complete.
*/
public class Solution {
public static int step; //static was added here
public static void main(String[] args) {
method1();
}
public static void method1() { //static was added here
method2();
}
public static void method2() { //static was added here
new Solution().method3();
}
public void method3() {
method4();
}
public void method4() {
step++;
for (StackTraceElement element : Thread.currentThread().getStackTrace())
System.out.println(element);
if (step > 1) return;
main(null);
}
}
答案 0 :(得分:2)
因为如果step
不是静态的,它将特定于method2
中创建的对象,并且总是从0开始,在{{1}增加后变为1 },method4
为false,所以在再次调用1 > 1
之前我们不会返回。所以程序会无休止地递归(好吧,无穷无尽,直到它溢出堆栈)。