所以我正在编写一个相当大的程序,并且有一个堆栈溢出错误(不,我没有使用任何类型的递归,至少没有直接使用。)我尝试用更简单的类重新创建这种情况,看看它是否也会导致堆栈溢出错误,结果确实如此。它们在这里:
头等舱:
public class Thing
{
public static void main(String[] args)
{
OtherThing thing = new OtherThing();
}
}
第二类:
public class OtherThing extends JPanel
{
protected int s =5;
protected String blah = "asfasd";
public OtherThing()
{
OtherOtherThing thing2 = new OtherOtherThing();
}
}
最后一个类:
public class OtherOtherThing extends OtherThing
{
public OtherOtherThing()
{
}
}
这会导致在 OtherThing 第 8 行和 OtherOtherThing 第 4 行之间发生堆栈溢出(我确信现在的行有点偏离。)
我知道你可以从一个继承自其他东西的类继承,Java API 中有很多这样的东西。这个例子有什么问题吗?
最佳答案
因为当创建 OtherOtherThing
时,会调用其父 OtherThing
的构造函数,从而创建一个新的 OtherOtherThing
,而在这个 OtherOtherThing
内部,它将依次创建一个新的 OtherOtherThing
...,这会导致 stackoverflow。
您可以使用延迟初始化或急切初始化来解决该问题:
延迟初始化:
public class OtherThing extends JPanel
{
protected int s =5;
protected String blah = "asfasd";
private OtherOtherThing other = null;
public OtherThing()
{
}
public void initialize(){
other = new OtherOtherThing();
}
}
急切初始化:
public class OtherThing extends JPanel
{
protected int s =5;
protected String blah = "asfasd";
private OtherOtherThing other = new OtherOtherThing();
public OtherThing()
{
}
}
关于java - Stack OverFlow 与继承的 JPanels,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28271287/