• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception in thread "main" java.lang.StackOverflowError

 
jose chiramal
Ranch Hand
Posts: 266
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The below code gives me an error :


 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15356
39
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your class Car has a number of Car objects as fields:

If you create a new Car object, it is going to initialize its fields, for example c1. But c1 is also a Car object that has three Car objects as fields. And each of those again have three Car objects as fields, etcetera ad infinitum. The JVM will recursively start creating all those Car objects until the stack overflows.
 
Sue Temple
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is because you are initializing the object within itself - when you create a car, it tries to create another car, that tries to create another car and goes into a recursive loop.

Move this code to to test()

 
Sue Temple
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry about a duplicate answer, but you just beat me there, Jesper - I did not see your post when until I hit submit!
 
jose chiramal
Ranch Hand
Posts: 266
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your replies.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic