I am trying to make two classes with each classes has an instantiation of another class, but havaing a java.lang.StackOverFlowError
. The first class looks like below
public class ReverseGPA {
GPpredictor gp_predictor = new GPpredictor(); //This is the line that causes error
double CURRENT_CREDITS;
double FUTURE_CREDITS;
double CUM_GPA;
double DESIRED_GPA;
double NEW_GRADE_POINT;
int ROUNDED_GRADE_POINT;
double NEW_GPS;
}
And the other class looks like this
public class GPpredictor {
ReverseGPA rev_gpa = new ReverseGPA(); //This is the line that causes error
ArrayList<String> arrayCourseName = new ArrayList<>();
ArrayList<Integer> arrayCourseCredit = new ArrayList<>();
ArrayList<String> arrayCourseGrade = new ArrayList<>();
int COURSES;
int CREDIT;
String COURSENAME;
//For predicting purposes
int GRADE;
}
I made it like this because i need to use the methods from the class ReverseGPA to be used in class GPpredictor (I need to use the grade points, by using the getter method)
Will be very thankful for any comments and helps
A stack overflow is a type of buffer overflow error that occurs when a computer program tries to use more memory space in the call stack than has been allocated to that stack.
A StackOverflowException is thrown when the execution stack overflows because it contains too many nested method calls. using System; namespace temp { class Program { static void Main(string[] args) { Main(args); // Oops, this recursion won't stop. } } }
StackOverflowError is an error which Java doesn't allow to catch, for instance, stack running out of space, as it's one of the most common runtime errors one can encounter.
You've got infinite recursion going on as the classes create instances of each other within themselves and so ReverseGPA creates a GPpredictor instance which creates a ReverseGPA which creates a GPpredictor which creates a ReverseGPA which creates a GPpredictor which creates a ReverseGPA which creates a GPpredictor ....
So in a concrete fashion, you have:
public class A {
B b = new B();
}
and
public class B {
A a = new A();
}
Stop the madness -- pass in an instance to at least one of these classes via a constructor parameter or setter method. I'm not sure what your classes do, so I can't say which (or if both) should do this.
Again, in a concrete fashion, have at least one do
public class A {
B b;
public void setB(B b) {
this.b = b;
}
}
and
public class B {
A a;
public B(A a) {
this.a = a;
}
}
And in the main method
public static void main(String[] args) {
A a = new A();
B b = new B(a); // pass a into B
a.setB(b); // pass b into A
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With