Reputation:
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;
}
}
Upvotes: 0
Views: 530
Reputation: 187
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.
Upvotes: 0
Reputation: 300825
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)
Upvotes: 12
Reputation: 8911
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;
}
}
Upvotes: 3
Reputation: 22477
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?
Upvotes: 0
Reputation: 351476
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.
Upvotes: 2