为什么我在构造函数中收到StackOverflowError异常 [英] Why am I getting a StackOverflowError exception in my constructor

查看:115
本文介绍了为什么我在构造函数中收到StackOverflowError异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class Cloning {

    Cloning c=new Cloning();
    public static void main(String[] args) {

        Cloning c=new Cloning();
        c.print();
    }

    public void print(){
        System.out.println("I am in print");
    }

}

在上面的代码我有一个简单类和类级实例,我也有一个同名的本地实例。运行上面的代码时,我得到以下异常:

In the above code I have a simple class and a class level instance, I also have a local instance with the same name. When running the above code I get below exception :

Exception in thread "main" java.lang.StackOverflowError
    at com.java8.Cloning.<init>(Cloning.java:6)


推荐答案

你的main方法创建一个克隆实例(克隆c = new Cloning(); ),这会导致实例变量的初始化 c Cloning c = new Cloning(); ),这会创建另一个克隆实例,依此类推......

Your main method creates a Cloning instance (Cloning c=new Cloning();), which causes the initialization of the instance variable c (Cloning c=new Cloning();), which creates another Cloning instance, and so on...

你有一个无限的构造函数调用链,导致 StackOverflowError

You have an infinite chain of constructor calls, which leads to StackOverflowError.


在上面的代码中,我有一个简单的类和一个类级实例

In the above code I have a simple class and a class level instance

您没有类级实例。您有一个实例级实例。如果你想要一个类级实例,请更改

You don't have a class level instance. You have an instance level instance. If you want a class level instance, change

Cloning c=new Cloning();

static Cloning c=new Cloning();

这篇关于为什么我在构造函数中收到StackOverflowError异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆