Adam
Adam

Reputation: 319

StackOverFlow Error on classes

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

Upvotes: 7

Views: 134

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285401

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
}

Upvotes: 9

Related Questions