Search code examples
javastack-overflow

Getting StackOverflow error and why?


Why I am getting StackOverflowError at line 11. The line that I am getting error: System.out.println(new JavaInnerClass().callInnerClassMethod(animalQuantity));

Here is the full code:

public class Dog extends Animal {
private String animalName;
private int animalQuantity;

public Dog(String animalName, int animalQuantity) {
    animalName(animalName);
    quantity(animalQuantity);
    // JavaInnerClass.tempDog name = new JavaInnerClass.tempDog();
    // System.out.println(name.totalQuantity(animalQuantity));
    System.out.println(new JavaInnerClass().callInnerClassMethod(animalQuantity));
}

@Override
public String animalName(String animalName) {
    this.animalName = animalName;
    return animalName;
}

@Override
public int quantity(int animalQuantity) {
    this.animalQuantity = animalQuantity;
    return animalQuantity;
}

}

the JavaInnerClass:

public class JavaInnerClass {

Dog[] dog = { new Dog("Husky", 90), new Dog("Boxer", 100) };

tempDog temp = new tempDog();

public static class tempDog {

    public int totalQuantity(int quantity) {
        return quantity + 200; // assuming a statement
    }

}

public int callInnerClassMethod(int quantity) {
    return temp.totalQuantity(quantity);
}

public static void main(String[] args) {
    new JavaInnerClass();
}

}


Solution

  • The JavaInnerClass constructor invokes the Dog constructor that invokes the JavaInnerClass constructor that invokes the Dog constructor ... and so on...


    Look at the JavaInnerClass constructor.

    It initializes the array field dog :

    Dog[] dog = { new Dog("Husky", 90), new Dog("Boxer", 100) };
    

    But what does the Dog constructor ?
    It creates an instance of JavaInnerClass :

    public Dog(String animalName, int animalQuantity) {
         ...
        System.out.println(new JavaInnerClass().callInnerClassMethod(animalQuantity));
    }
    

    And all that goes on until the stackoverflow.