0

我有一个简单的 Java 理论问题。如果我编写一个包含 main() 方法和其他一些方法的类,并在该 main 方法中调用该类的实例(比如 new Class()),我有点困惑为什么不发生递归. 假设我正在编写一个绘图程序,类中的其他方法创建一个窗口并绘制数据;在 main 方法中,我调用了类本身的一个实例,但只出现了一个窗口。太好了,这正是我想要的,但直觉表明,如果我从自身内部创建类的实例,则应该发生某种递归。是什么阻止了这一点?这是一个示例(在我看来,我想知道是什么阻止了不必要的递归):

     public class example{
         method1(){create Jpane}
         method2(){paint Jpane}
         method 3(){do some computations}

         public static void main(String[] args){
            new example(); // or create Jblah(new example()); 
         }
      }
4

4 回答 4

8

我认为您将main方法(只是程序的入口点)与构造函数混淆了。

例如,如果你写:

public class Example {
    public Example() {
        new Example(); // Recursive call
    }

    public static void main(String[] args) {
        // Will call the constructor, which will call itself... but main
        // won't get called again.
        new Example(); 
    }
}

然后那爆炸。

于 2013-02-07T18:41:48.897 回答
1

当您实例化一个类时,该main方法不会自动执行。它可以简单地用作应用程序的入口点 - 然后将执行一次。

于 2013-02-07T18:41:33.887 回答
1

Recursion isn't a bad thing. I suspect you are asking why there isn't an infinite recursion.

The big concept you are missing is that when you call new Example() you are allocating memory and then invoking just one method (the constructor). The main() is only invoked at the start of the whole program unless you explicitly call it.

--- edited to add

public class MyMainClass {
  public static void main(String arg[]) {
    Calculator c = new Calculator();
    int x = c.factorial(5);
  }
}

class Calculator {

  Calculator() { }

  public int factorial(int x) {
    if (x > 1) return x * factorial(x - 1);
    else return 1; // WARNING: wrong answer for negative input
  }
}

Since factorial doesn't use any instance variable, it could have been declared static and called as Calculator.factoral(5); without even using new, but I din't do that since showing off new was the whole point of the example.

于 2013-02-07T18:43:41.257 回答
0

仅仅因为你在类中有一个 main 方法并不意味着每次创建类时都会调用它。

Java 寻找 main 作为程序的入口点,并在启动时调用它。您从它们实例化的任何对象都不会调用 main,因为就 java 而言,它已经完成了创建程序入口点的工作。

于 2013-02-07T18:42:17.157 回答