问题描述
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
.
您没有类级实例。您有一个实例级实例。如果你想要一个类级实例,请更改
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异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!