Why am I receiving a stack overflow?

混江龙づ霸主 提交于 2019-12-02 07:25:14

Item creates SlayerProgram:

SlayerProgram sp = new SlayerProgram();

And SlayerProgram creates Item

Item item = new Item(name,price,amount);

And therefore on initialization you will create those objects endlessly

There's a similar Baeldung example for getting StackOverflowError

This ends up with a StackOverflowError since the constructor of ClassOne is instantiating ClassTwo, and the constructor of ClassTwo again is instantiating ClassOne.

Because there is a circular dependency between Item and SlayerProgram class. You have created Item item = new Item(name,price,amount); in class SlayerProgram and SlayerProgram sp = new SlayerProgram(); in class Item. So when you try to create the object of Item it will try to create the object of SlayerProgram and then SlayerProgram try to create the object of Item and it goes on still the method stack is not full and leads to StackOverflow.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!