i would like to resolve problem which i am getting on making on object of nested class doctor1 [duplicate]

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 ?


Solution 1:

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