Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack Overflow error when constructing a new object in Java

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.

like image 781
Drake Avatar asked Sep 01 '26 23:09

Drake


1 Answers

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);
}
like image 50
MByD Avatar answered Sep 03 '26 13:09

MByD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!