StackOverFlow error in classes

I am trying to make two classes with each class, has an instance of another class, but havaing java.lang.StackOverFlowError . First grade looks lower

 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 another class is as follows

 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 did it like this because I need to use methods from the ReverseGPA class that will be used in the GPpredictor class (I need to use evaluations using the getter method)

Any comments and suggestions will be greatly appreciated.

+7
java
source share
1 answer

Your infinite recursion continues because the classes instantiate each other within themselves, so ReverseGPA creates an instance of GPpredictor that creates a ReverseGPA that creates a GPpredictor that creates a ReverseGPA that creates a GPpredictor that creates a ReverseGPA that creates a GPpredictor ....

So, in a specific form, you have:

 public class A { B b = new B(); } 

and

 public class B { A a = new A(); } 

Stop Madness - Pass an instance to at least one of these classes using the constructor parameter or the setter method. I'm not sure what your classes do, so I can't say what (or if both of them) should do this.

Again, in a concrete way, at least one

 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 } 
+7
source share

All Articles