Why can I get a StackOverflowError?

Why is this java code creating StackOverflowError? I understand that this has something to do with the recursive typical type parameter. But I do not understand the whole mechanism.

public class SomeClass<T extends SomeClass> {

    SomeClass() {
        new SomeClassKiller();
    }

    private class SomeClassKiller extends SomeClass<T> {
    }

    public static void main(String[] args) {
        new SomeClass();
    }
}
+3
source share
6 answers

The general part does not matter - and it does not matter that the class is nested. Look at this almost equivalent pair of classes, and this should be more obvious:

public class SuperClass
{
    public SuperClass()
    {
        new SubClass();
    }
}

public class SubClass extends SuperClass
{
    public SubClass()
    {
        super();
    }
}

Thus, the subclass constructor calls the superclass constructor, which then creates a new subclass, which calls the superclass constructor, which creates the new subclass, etc. bang!

+13
source

, , .

public class SomeClass<T extends SomeClass> {

    SomeClass() {//A
        new SomeClassKiller();// calls B
    }

    private class SomeClassKiller extends SomeClass<T> {//B
               //calls A
    }

    public static void main(String[] args) {
        new SomeClass(); //calls A
    }
}
+2

, SomeClass SomeClassKiller.

+1
public class SomeClass<T extends SomeClass> {

    SomeClass() {
        new SomeClassKiller();
    }

    private class SomeClassKiller extends SomeClass<T> {
       public SomeClassKiller()
       {
         super(); //calls the constructor of SomeClass
        }
    }

    public static void main(String[] args) {
        new SomeClass();
    }
}

, , , , u , SomeClass SomeClassKiller .

0

, A B, (B).

new SomeClassKiller() SomeClass, , , SomeClassKiller... .

0

The method main()creates a new instance SomeClassthat calls the constructorSomeClass , which creates a new instance SomeClassKiller, which by default calls the parent constructor and stackoverflow takes place.

To avoid stackoverflow. Modify the code to look like this:

public class SomeClass<T extends SomeClass> {

    SomeClass() {
        new SomeClassKiller();
    }

    private class SomeClassKiller extends SomeClass<T> {
        public SomeClassKiller(){
            //super(); does this by default, but is now commented out and won't be called.
        }

    }

    public static void main(String[] args) {
        new SomeClass();
    }
}
0
source

Source: https://habr.com/ru/post/1780849/


All Articles