简体   繁体   中英

StackOverflowError caused by non-static member of same type

The code in the following snippet throws java.lang.StackOverflowError .

public class Main
{
    private Main m=new Main("");  //This statement causes the exception.

    private Main(String s)
    {
        System.out.println(s);
    }

    public static void main(String[] args)
    {
        try
        {
            Main m1=new Main("The constructor called.");
            System.out.println("Successful!");
        }
        catch (Exception ex)
        {
            System.out.println(ex);
        }
    }
}

There is no meaning to deliberately write this statement private Main m=new Main(""); inside the class itself but that statement is not ever supposed to be used by any code in the class then how can that statement cause the exception to be thrown?

Each time you call the constructor, you create an instance and thus execute the initializing code

private Main m=new Main("");

which calls the constructor, etc.

You probably want

private static Main m=new Main("");

in order to keep a singleton.

程序会导致堆栈溢出是绝对正常的……编译器不会检查代码中是否使用了成员m,尽管您说对了,但它可能已经这样做了,可能会有副作用:没有生成对象。 ..为了构造一个Main对象,必须构造另一个Main对象(私有Main m成员)...,它给出无限递归,因此堆栈oveflow

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