Reputation: 49
I am newbie in Java. Can anyone explain to me why it show StackOverflowError ?
public class MainClass {
static Start st = new Start();
public static void main(String[] args) {
st.start();
}
}
public class Start {
Generator objGenerator = new Generator();
void start() {
objGenerator.generator();
}
}
public class Generator extends Start {
void generator() {
//...
}
}
If Generator class is not inherited from class Start, everything is ok, but why ?
Upvotes: 0
Views: 441
Reputation: 68
The reason for the StackOverflow error is because the recursive instantiation of objects does not terminate. The recursive object intstantiation is as follows.
Step 1: static Start st = new Start();
Step 2: Instantiating a Start object requires instantiating a Generator object due to the initialization of the member variable objGenerator.
Generator objGenerator = new Generator();
Step 3: Since Generator is a subclass of Start, instantiating a Generator object requires instantiating Start object, which is going back to step 2.
So in effect you are in a infinite loop going back and forth between step 2 and step 3. Upon hitting the stack limit, the StackOverflow exception is thrown.
Upvotes: 0
Reputation: 1337
When an Instance of Generator
is created, the constructor of Start
is called because Generators
extends
Start
. This is called constructor chaining.
However, when you call the constructor of start
you also have a variable thats call new Generator
...
You create a Generator
that is a Start
that creates a Generator
that is a Start
... and its goes on until your stack overflows
Upvotes: 1
Reputation: 61158
Generator
inherits from Start
class Generator extends Start
And Start
creates a Generator
on construction:
Generator objGenerator = new Generator();
Which is the same as the following:
public class Start {
Generator objGenerator;
public Start() {
objGenerator = new Generator();
}
}
Start
has constructor that runs objGenerator = new Generator()
.
This calls the constructor for Generator
.
The first thing that the constructor for Generator
does is call super()
.
super()
is default constructor for Start
.
GOTO 1.
Upvotes: 0