Java 为什么这个代码有效?添加静态关键字的任务
有人能告诉我为什么这样做吗?任务是添加最少的静态关键字以使代码正常工作。我可以理解method1和method2的静态特性,但为什么要将其添加到int步骤Java 为什么这个代码有效?添加静态关键字的任务,java,static,Java,Static,有人能告诉我为什么这样做吗?任务是添加最少的静态关键字以使代码正常工作。我可以理解method1和method2的静态特性,但为什么要将其添加到int步骤 /* 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
/* 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);
}
}
因为如果
step
不是静态的,它将特定于在method2
中创建的对象,并且总是从0开始,在被method4
递增后变为1,1>1
为false,因此我们在再次调用main
之前不会返回。因此,程序将无休止地递归(好吧,直到它溢出堆栈为止)。哇,这是一个多么可怕的代码示例。谁把这个强加给你的?不需要编译,但需要让它终止。。。但正如T.J.克劳德所说,这太可怕了。为什么?这只是java培训课程中的一些任务