我有一个简单的Java理论问题.如果我编写一个包含main()方法的类以及其他一些方法,并且在该main方法中调用该类的实例(比如新的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());
}
}
Run Code Online (Sandbox Code Playgroud)
我认为你把这个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();
}
}
Run Code Online (Sandbox Code Playgroud)
那会爆炸.