2

I'm trying to construct a PackingCase object with a certain set of values. While the program shows no errors during coding, when running, I get this error;

Exception in thread "main" java.lang.StackOverflowError
at assignment.pkg2.PackingCase.<init>(PackingCase.java:59)
at assignment.pkg2.PackingCase.<init>(PackingCase.java:60)

My code is as follows;

public class PackingCase {
// private fields go here

int serialNumber;
int timesUsed;
int timeCreated;
int timeStored;
String name;
String description;


void setCase(int s, int TU, int TC, int TS){
    serialNumber = s;
    timesUsed = TU;
    timeCreated = TC;
    timeStored = TS;

}

double volume(){
    return serialNumber*timesUsed*timeCreated*timeStored;
}

public PackingCase(){ 
    PackingCase PC1 = new PackingCase();
    double vol;

    PC1.setCase(1, 2, 3, 4);

    vol = PC1.volume();
    System.out.println(""+vol);




}

Line 59 is "public PackingCase(){" , and Line 60 is "PackingCase PC1 = new PackingCase();". I have no idea what's going on, considering that an example I found uses virtually the same code structure, and compiles with no errors whatever. Any help would be appreciated.

1
  • 1
    +1: stack overflow error message
    – user684934
    Commented Jul 25, 2011 at 6:00

4 Answers 4

10

Each creation of a new object leads to the creation of another new object (and so on...) until the stack is overflowed.

Instead, it should be look like that:

public PackingCase(){ 
    this.setCase(1, 2, 3, 4);
    vol = this.volume();
    System.out.println(""+vol);
}
1
  • @pst - pedantic doesn't need to be followed by "but...". Thanks!]
    – MByD
    Commented Jul 25, 2011 at 4:49
3

You have a recursive call in the constructor. Leave the constructor empty (simply delete it) and run this code from main method:

public static void main(String[] a){
    PackingCase pc1 = new PackingCase();
    pc1.setCase(1, 2, 3, 4);
    double vol = pc1.volume();
    System.out.println(""+vol);
}
1
public PackingCase(){      PackingCase PC1 = new PackingCase(); ...}

Constructor recursively calls itself, causing stackoverflow.

0

You are calling new within the handler for new, creating an infinite loop (and since the stack is finite, it eventually runs out of space). But public PackingCase() { ... } is a constructor. That means it is only called when someone has already used new PackingCase(). The code within the constructor doesn't have to create the object (allocate space), just initialize it (set values for its fields).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.