这是我的代码; 导致StackOverflow错误:
public class NucleousInterviewQuestion {
NucleousInterviewQuestion interviewQuestion = new NucleousInterviewQuestion();
public NucleousInterviewQuestion() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
NucleousInterviewQuestion interviewQuestion= new NucleousInterviewQuestion();
}
}
Run Code Online (Sandbox Code Playgroud)
这里:
public class NucleousInterviewQuestion {
NucleousInterviewQuestion interviewQuestion = new NucleousInterviewQuestion();
Run Code Online (Sandbox Code Playgroud)
创造了无尽的递归.
关键是:你打电话给new你的主要方法.执行此操作时,运行属于此类的"init"代码."init"代码包括:
你有一个具有init代码的字段...... new再次调用; 对于同一个班级.
在这个意义上的"解决方案":了解如何初始化类.当然,类可以有引用其他对象的字段; 甚至是同一类的对象; 但是你需要(例如)类似的东西:
public class Example {
Example other;
public Example() {
other = null;
}
public Example(Example other) {
this.other = other;
}
Run Code Online (Sandbox Code Playgroud)
这样您就可以引用同一个类中的另一个对象; 没有创建递归.
| 归档时间: |
|
| 查看次数: |
2212 次 |
| 最近记录: |