Answer the question
In order to leave comments, you need to log in
How to fix a specific case with stackoverflow? How to understand java?
Tell me, please, why, damn it, the classes in this example depend on each other.
Or rather, the Lois class from the Pitter class. The problem is that a stack overflow occurs and the program throws an error. I am a beginner and please do not swear for my possibly stupid mistakes.
Answer the question
In order to leave comments, you need to log in
These classes depend on each other, because one creates an instance of the other, and vice versa. In itself, this is not scary, but it happens to you both there and there right in the initialization (the place where the fields are declared and they are immediately assigned a new instance of another class).
public class Lois {
Pitter husbend = new Pitter();
...
public class Pitter {
Lois wife = new Lois();
...
... = new Lois();
//or
... = new Pitter();
public class Main {
public static void main(String[] args) {
// You can run JVM with:
// -XX:MaxJavaStackTraceDepth=-1 (unlimited number of stack trace frames)
// -Xss4m (play around with stack size)
//
try {
first(); // causes stack overflow!
} catch (StackOverflowError e) {
System.err.println("Depth (frames):" + e.getStackTrace().length);
}
}
static int first(){
return second();
}
static int second(){
return first();
}
}
public class Lois {
Pitter myHusband = new Pitter(this);
public Lois(Pitter whoIsMyHusband){
myHusband = whoIsMyHusband;
}
//...
}
public class Pitter {
Lois myWife = new Lois(this);
public Pitter(Lois whoIsMyWife) {
myWife = whoIsMyWife;
}
// ...
}
Most likely, when creating Lois, new Pitter is called, when it is created, new Lois is called, when it is created, new Pitter is called ... Repeat until the stack overflows.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question