Search code examples
javainheritancestack-overflow

Stack Overflow Error in the constructor of a subclass


My Superclass is:

public abstract class MarketProduct {
private String name;

public MarketProduct(String productName) {
name = productName;
}

public final String getName() {
return this.name;
}

public abstract int getCost();

public abstract boolean equals(Object o);
}

And my subclass (up until its constructor) is:

public class Egg extends MarketProduct {
 private int numEggs;
 private int priceEggs;

 public Egg(String productName, int numRequired, int priceEggsDozen) {
 super(productName); 
 numEggs = numRequired;
 priceEggs = priceEggsDozen;
 MarketProduct marketProductEgg = new Egg(productName, numEggs, priceEggs);
 }

I am getting a java.lang.StackOverflowError at Egg.init(Egg.java:9). Line 9 in this case is the last line of the constructor in the subclass, i.e:

MarketProduct marketProductEgg = new Egg(productName, numEggs, priceEggs);

I understand that a stack oveflow error arises when a recursive method keeps getting called. So I assumed that may have been a problem with the "this" in the getName method of the superclass. But removing it still caused the error at runtime. I feel that their is a problem in the structure of the code in my subclass constructor, but I am not sure what exactly. I tried to create the object higher up with the original variables, but to no avail.

Any help?


Solution

  • You're creating a new Egg in the Egg constructor when you write

    MarketProduct marketProductEgg = new Egg(productName, numEggs, priceEggs);
    

    That means every time you make an Egg, the constructor will run, then in the constructor you create a new egg, which causes the constructor to run again and create a new egg, then the constructor runs again, which causes a new egg to be created, then the constructor runs again...

    You see the point here. Every time an egg is created, another egg will be created, until you have infinite eggs (or you run out of stack space, causing a StackOverflowError).

    Since you never use marketProductEgg, just get rid of it from the constructor.

    And just to prove that this has nothing to do with subclassing, take this class:

    class A {
       A() {
         A(); // Creates a new A in the constructor of A
       } 
    }
    

    And try to create an instance of it. Every A creates another A, which creates another A, which creates another A...