java StackOverflowError when local and instance objects creation

女生的网名这么多〃 提交于 2019-11-27 02:18:49
Colin Hebert

Let's see what will be executed :

  1. main() create a new instance of ObjectTest
  2. the ObjectTest class has a field instanceObj which will contain an ObjectTest
  3. the instanceObj in initialized with a new ObjectTest
  4. go to step 2

I think you wanted something more like this :

public class ObjectTest {
    private static ObjectTest instanceObj;

    private ObjectTest() {
    }

    public static ObjectTest getInstance() {
        if (instanceObj != null) {
            instanceObj = new ObjectTest();
        }
        return instanceObj;
    }

    public static void main(String[] args) {

        ObjectTest localObj = ObjectTest.getInstance();
    }
}

Or this :

public class ObjectTest {
    private static final ObjectTest instanceObj = new ObjectTest();

    private ObjectTest() {
    }

    public static ObjectTest getInstance() {
        return instanceObj;
    }

    public static void main(String[] args) {

        ObjectTest localObj = ObjectTest.getInstance();
    }
}

This is the Singleton pattern.


On the same topic :

You call the constructor to create a new instance of your object. It has a reference to another instance, which you initialize with another new instance of ObjectType which, in turn, does the same thing. it's an infinite number of calls until you get that error.

This will work.

public class ObjectTest { 

  public ObjectTest() { 

   } 


  public static void main(String[] args) { 

     ObjectTest localObj = new ObjectTest(); 
   } 
} 

Every ObjectTest instance refers to another ObjectTest—named instanceObj. This instance is constructed when its "parent" instance is created… and thus results in construction of another, and another, ad infinitum.

Here is equivalent code that may point out the flaw more clearly:

public class ObjectTest {

  ObjectTest instanceObj;

  public ObjectTest() {
    instanceObj = new ObjectTest(); /* Recursively call the constructor. */
  }

}

Because you are recursively creating yourself.

You need to inject your instance, or have some other class manage that property.

public class ObjectTest {

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