Search code examples
javastack-overflow

StackOverflowError when try create new object of inherit class in superclass


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

  • 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();
        }
    }
    

    1. Start has constructor that runs objGenerator = new Generator().

    2. This calls the constructor for Generator.

    3. The first thing that the constructor for Generator does is call super().

    4. super() is default constructor for Start.

    5. GOTO 1.