简体   繁体   中英

Why it throws stackOverflowError when the getInstance method is not static

Class A Sample 1

public class A {

    private  A instance = new A();

    public A() {
    }

    public  A getInstance() {
        return instance;
    }

}

Class A Sample 2

public class A {

    private static A instance = new A();

    public A() {
    }

    public static A getInstance() {
        return instance;
    }
}

Main Class

    public class MainClass {


      public static void main(String[] args) {
        A a = new A();
     }

}

When I try to run above program with using Class A Sample 1, it throws stackOverflowError Exception but when I try to run with using Class A Sample 2 it run without any errors. Anyone who can explain to me with details why it throws error when I using Class A sample 1? Thank you.

private A instance = new A();

public A() {
}

This is equivalent to code which calls new A() in the constructor. It's effectively the same as:

private A instance;

public A() {
    this.instance = new A();
}

Do you see how this causes infinite recursion? The constructor A() invokes itself.


private static A instance = new A();

On the other hand, when you have a static variable it's only instantiated once when the class itself is loaded, rather than every time an instance of the class is created. It's as if you had done it in a static initialization block—which only runs a single time.

private static A instance;

static {
    A.instance = new A();
}

Notice how this.instance has become A.instance . There's only a single class-wide instance variable here versus a per-instance copy in the other version.

因为在非static情况下,您每次创建新A 都会调用new A()

Sample 1 causes an infinite loop since every time you create an instance of A it will create another instance of A until you run out of stack space. Since you use static in Sample 2 the member variable instance will be created once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM