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.pkg开发者_开发技巧2.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.
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);
}
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);
}
public PackingCase(){ PackingCase PC1 = new PackingCase(); ...}
Constructor recursively calls itself, causing stackoverflow.
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).
精彩评论