StackOverflowError in instance initializer

This question is more theoretical. So I have the following code:

public class Test {

    public static void main(String[] args) {
        Test test = new Test();
    }

    {
        System.out.println("Instance execution");
    }
}

It compiles and prints "Run Instance". But when I try to execute some other method as follows:

public class Test {

    public static void main(String[] args) {
        Test test = new Test();
    }

    {
        System.out.println("Instance execution");
    }

    private void anotherMethod() {
        System.out.println("Method execution");
    }

    {
        Test test = new Test();
        test.anotherMethod();
    }
}

This gives me this error:

Exception in thread "main" java.lang.StackOverflowError
at Test.<init>(Test.java:15)

I am fully convinced that this error has the simplest explanation, but my question here is, is there a constructor that throws this error? Or can only system methods be executed? This whole approach of the executable Instance Initializer is very new to me, so any help would be greatly appreciated. Thank.

+4
source share
2 answers

It:

{
    Test test = new Test();
    test.anotherMethod();
}

- . Test. Test, , , , Test, ... .

, ?

, . , , , ( , ) super ( , ). , , , , .

?

, " ", , . , , static:

public class Test {

    public static void main(String[] args) {
        Test test = new Test();
    }

    {
        System.out.println("Instance execution");
    }

    private void anotherMethod() {
        System.out.println("Method execution");
    }

    static // <==================
    {
        System.out.println("Class initialization"); // ***
        Test test = new Test();
        test.anotherMethod();
    }
}

:

Class initialization
Instance execution
Method execution
Instance execution

( " " , new Test main, static.)

anotherMethod main:

public class Test {

    public static void main(String[] args) {
        Test test = new Test();
        test.anotherMethod();
    }

    {
        System.out.println("Instance execution");
    }

    private void anotherMethod() {
        System.out.println("Method execution");
    }
}

Instance execution
Method execution
+6

, obejct , .

this.anotherMethod();
+1

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


All Articles