[英]StackOverFlow error - from instantiating my object class
我試圖用Java創建一個類,該類構建一個Action
類型的對象,該對象具有三個int並將其返回到數組history
中的另一個類,其中history
是Action
類型的數組。 當它被調用時,我立即得到一個無限循環。 因此堆棧溢出。
錯誤-我打印了1行,然后繼續...
Exception in thread "main" java.lang.StackOverflowError
at sudokugame.Action.<init>(Action.java:7)
類:
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;
}
}
您的構造函數會永遠遞歸地調用自身。 溢出堆棧的肯定方法:)
public Action(int i, int o, int p){
//why do you do this?
a = new Action(i,o,p);
}
也許您真正想做的只是將i,o和p存儲在類實例中?
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 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;
}
}
問題在這里:
a = new Action(i,o,p);
您正在為類本身的構造函數中的新實例再次調用構造函數。 由於每次對構造函數的后續調用都會創建一個新的構造函數調用,因此堆棧無法展開,因此會導致堆棧溢出。
您實例化類本身。
您的Action類是否真的需要保留對另一個Action的引用?
Action a;
具體來說,這行是必要的嗎? 您用它做什么?
確保您的構造函數具有遞歸調用。
命令設計模式是一種處理情況的方法,其中您希望擁有執行的操作的歷史記錄,以便可以撤消操作等。
構造函數有遞歸調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.