问题
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 ?
回答1:
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 runsobjGenerator = new Generator()
.This calls the constructor for
Generator
.The first thing that the constructor for
Generator
does is callsuper()
.super()
is default constructor forStart
.GOTO 1.
回答2:
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
回答3:
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.
来源:https://stackoverflow.com/questions/49709691/stackoverflowerror-when-try-create-new-object-of-inherit-class-in-superclass