简体   繁体   中英

Why can't you instantiate the same object of that class inside constructor?

public class Run{
 public static void main(String... args){
      A a1 = new A();
 }
}

class A{
  public A(){
    A a = new A();
  }
  //here as well A a = new A();
}

Why does this give a java.lang.StackOverflowError ? Is there a recursive call happening here? How does it happen?

您正在构造函数内部调用构造函数,这就是new所做的事情,构造了一个新对象。

Is there a recursive call happening here?

Yup

How it happens?

When you new A() , it calls the constructor for A , which does a new A() which calls the constructor, which does a new A() ... and so on. That is recursion.

You can call, but it would be a recursive calling which will run infinitely. That's why you got the StackOverflowError .

The following will work perfectly:

public class Run{

 static int x = 1;
 public static void main(String... args){
      A a1 = new A();
 }
}

class A{
   public A(){
     if(x==1){
        A a = new A();
        x++;
    }
  }
}

The issue is that when you call the constructor, you create a new object (which means that you call the constructor again, so you create another object, so you call the constructor again...)

It is infinite recursion at its best, it is not related to it being a constructor (in fact you can create new objects from the constructor).

基本上,您的构造函数都不会退出-每个构造函数都会尝试递归实例化另一个A类型A对象。

You need to change your constructor to actually create an A object. Suppose A holds an integer value and nothing more. In this case, your constructor should look like this:

class A{
  int number;
  public A(){
      number = 0;
  }
}

What you're doing in your code is actually creating a new object instance inside of your own constructor.

So, when you call new A() , you're calling the constructor, which then calls new A() inside of its body. It ends up calling itself infinitely, which is why your stack is overflowing.

I would think that there's a recursive call there. In order to create an A, you have to create another A inside of it. But to create that A inside of it, you have to create a third A inside of that A. And so on. If you use two different constructors or arguments or something though, you should be able to work around this:

class A {
    public A(boolean spawn){
        if (spawn) {
            A a = new A(false);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM