Why am I receiving a stack overflow?

2020-04-26 13:12发布

问题:

My first block of code is my Item Object file; the second is the Main Class. Before there was not any issues with the code running but after I had added a read and write file my code had started to receive a stack flow error. just the snippet of which the error is being called.

    public class Item implements java.io.Serializable {

    public static String name;
    public static double price;
    public static double amount;
    public int max = 1;
    SlayerProgram sp = new SlayerProgram();
    ReadFile rf = new ReadFile();
    public Item(String name, double price,double amount )
    {
    this.name = name;
    this.price = price;
    this.amount = amount;

    }

    public void ItemSet(String name, double price,double amount)
    {
    this.name = name;
    this.price = price;
    this.amount = amount  
    }

My Main class:

    public class SlayerProgram {
//import file txts, and Item Class

        static String name;
        static double price;
        static double amount;
 Item item = new Item(name,price,amount);
ReadFile rf = new ReadFile();
static String fileNameText = "D:\\Game\\SlayerProgram\\Name.txt";
static String filePriceInt = "D:\\Game\\SlayerProgram\\Price.txt";
static String fileAmountInt ="D:\\Game\\SlayerProgram\\Amount.txt";

   //begin file Read   

public void BeginText() throws IOException
{
    TextFile();
}

public void Max()
{
    item.Max();
}

    //declare needed Data Types;
        final int max = item.max;
        ArrayList<String> Name  = new ArrayList<>();
        ArrayList<Double> Price = new ArrayList<>();
        double size = Price.size();
        ArrayList<Double> Amount = new ArrayList<>();


Exception in thread "main" java.lang.StackOverflowError
at slayerprogram.Item.<init>(Item.java:18)
at slayerprogram.SlayerProgram.<init>(SlayerProgram.java:25)
at slayerprogram.Item.<init>(Item.java:18)
at slayerprogram.SlayerProgram.<init>(SlayerProgram.java:25)

How can I find where the stack overflow is being caused?

回答1:

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.



回答2:

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.