• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java stack overflow error  RSS feed

 
Louis Lewis
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, I am trying to create a project with two classes; a main one and a secondary one. However, I started getting a stack overflow error when I treeid to create an object of the secondary class in both the main and the secondary class. I made a super simplified version of it to see if there was something else I was doing wrong, but I'm still getting the same error, and I don't understand why. Here is the simplified version:

public class TestProject
{

public static void main(String[] args)
{
TestClass object1 = new TestClass;
}
}

public class TestClass
{
TestClass object2 = new TestClass;
}

When I try to run it in netbeans, it tells me that there is a stack overflow error on the line containing the second object creation: "TestClass object2 = new TestClass;". Another seemingly relevant fact is that the error goes away when I comment out either object creation (the one in the main or the secondary class). Does anyone know why I might be getting this error and/or how to solve it?
 
Ivan Jozsef Balazs
Rancher
Posts: 999
5
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Every instance of TestClass has a member called object2 of the same type.
Now when such an object is being constructed, its member object2 has to constructed too.
However, it also has an object2, which has to be constructed.
However, it also has an object2, which has to be constructed.
However, it also has an object2, which has to be constructed.
However, it also has an object2, which has to be constructed.
However, it also has an object2, which has to be constructed.
However, it also has an object2, which has to be constructed.
...
...
(stack overflow)

 
manish ghildiyal
Ranch Hand
Posts: 136
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your code triggers a non-ending chain of constructor call...hence the error.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!