0

I am trying to make a class in Java that builds an object of type Action which holds three ints and returns it to my other class in the array history, where history is an array of type Action. When it is called I immediately get an endless loop; hence the stack overflow.

Error - I printed 1 line, it goes on...

Exception in thread "main" java.lang.StackOverflowError
    at sudokugame.Action.<init>(Action.java:7)

Class:

public class Action {

    Action a;
    public Action(int i, int o, int p){
      a = new Action(i,o,p);
    }

    public void   setAction(int n, int b, int c){

    }

    public Action  getAction(){
        return a;
    }
}

8 Answers 8

12

Your constructor calls itself recursively forever. A sure way to overflow a stack :)

public Action(int i, int o, int p){
    //why do you do this?
    a = new Action(i,o,p);
}

Maybe what you really wanted to do was just store i,o and p in the class instance?

public class Action {

  int i;
  int o;
  int p;

  public Action(int i, int o, int p){
    this.i = i;
    this.o = o;
    this.p = p;
  }

  ...
}

(edit: see other answer for fuller example)

Sign up to request clarification or add additional context in comments.

Comments

3

Try doing it this way:

public class Action {

  int i;
  int o;
  int p;

  public Action(int i, int o, int p){
    this.i = i;
    this.o = o;
    this.p = p;
  }

  public void setAction(int n, int b, int c){
    this.i = i;
    this.o = o;
    this.p = p;
  }

  public Action getAction(){
    return this;
  }
}

Comments

2

The problem is here:

a = new Action(i,o,p);

You are invoking the constructor again for a new instance inside the constructor of the class itself. Since each subsequent call to the constructor will create a new constructor call there is no way for the stack to unwind, therefore creating a stack overflow.

Comments

0

Your instantiating the class within itself.

1 Comment

Why would this be a problem? The recursion is the problem here.
0

Does your Action class really need to hold on to a reference to another Action?

Action a;

Specifically, is this line necessary? What are you using it for?

Comments

0

sure your constructor has recursive call.

Comments

0

The Command design pattern is one way to approach a situation where you want to have a history of actions taken so they can be undone, etc.

Comments

0

Constructor have recursive call.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.