Stack Overflow Error in the constructor of a subclass [duplicate]

僤鯓⒐⒋嵵緔 提交于 2021-02-04 21:07:27

问题


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?


回答1:


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...




回答2:


As @Lucio mentioned, put this line MarketProduct marketProductEgg = new Egg(productName, numEggs, priceEggs); outside of the constructor, you are creating a lot of objects when you put that line in the constructor.



来源:https://stackoverflow.com/questions/52572996/stack-overflow-error-in-the-constructor-of-a-subclass

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