| Author |
Exception in thread "main" java.lang.StackOverflowError
|
jose chiramal
Ranch Hand
Joined: Feb 12, 2010
Posts: 266
|
|
The below code gives me an error :
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12911
|
|
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.
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
Sue Temple
Greenhorn
Joined: May 01, 2010
Posts: 19
|
|
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
Joined: May 01, 2010
Posts: 19
|
|
|
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
Joined: Feb 12, 2010
Posts: 266
|
|
|
Thanks for your replies.
|
 |
 |
|
|
subject: Exception in thread "main" java.lang.StackOverflowError
|
|
|