An endless cycle problem of Java

look at the first paragraph of code

public class Test {

    public Test test = new Test();

    public void say() {
        System.out.println("hello world!");
    }

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

the above code will cause a dead loop and lead to a memory overflow. Let"s take a look at the second code

public class Test {

    public static Test test = new Test();

    public void say() {
        System.out.println("hello world!");
    }

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

in the second section of code above, new Test (). Test.say (); can be referenced indefinitely, but is there an endless loop? why? Can someone analyze the second kind of code from a memory point of view?

Mar.28,2021

the first code new Test () executes public Test test = new Test (); , and then goes on to new Test () , resulting in endless loop, infinite instantiation, and finally memory overflow.
the second section of code public static Test test = new Test (); is executed when the class is loaded, and is not repeated each time new Test () , so the instantiation variable


new Test (). Test.say () = = new Test (). Say () = = Test.say ()
new Test (). Test.test = = new Test (). Test = = Test.test is not repeated. No matter how many times you call .test, it points to a heap address.


the first segment code is to create an object wirelessly, and each time memory is consumed to create a new object

the second paragraph of code is similar to the cross-reference between two objects, with no new objects generated and no memory consumption
An a = new A ();
B b = new B ();
a.b = b;
b.a = a;
so that a.b.a.b.a.b can be referenced wirelessly, but no matter how many layers are written, these two objects are referenced

.

static is a static class variable with only one copy. Although you are an object from new, you can also call class variables.

Menu