简体   繁体   English

由相同类型的非静态成员引起的StackOverflowError

[英]StackOverflowError caused by non-static member of same type

The code in the following snippet throws java.lang.StackOverflowError . 以下代码段中的代码引发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(""); 故意将这个语句写成private Main m=new Main("");没有意义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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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