java StackOverflowError when local and instance objects creation
Solution 1:
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();
}
}
Solution 2:
Let's see what will be executed :
-
main()
create a new instance ofObjectTest
- the
ObjectTest
class has a fieldinstanceObj
which will contain anObjectTest
- the
instanceObj
in initialized with a newObjectTest
- 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 :
- Why I'm getting StackOverflowError
- Circular dependency in java classes
Solution 3:
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. */
}
}
Solution 4:
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;
}
}