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

懵懂的女人 提交于 2021-02-17 05:15:52

问题


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?


回答1:


You're calling the constructor inside the constructor--that's what new does, constructs a new object.




回答2:


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.




回答3:


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++;
    }
  }
}



回答4:


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).




回答5:


Basically none of your constructors will ever exit - each will get as far as trying to instantiate another object of type A recursively.




回答6:


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.




回答7:


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);
        }
    }
}


来源:https://stackoverflow.com/questions/11364043/why-cant-you-instantiate-the-same-object-of-that-class-inside-constructor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!