与构造函数有一些问题?

时间:2012-08-29 13:26:11

标签: java exception inheritance stack-overflow extend

我在构建类时遇到问题,

以下代码抛出异常

public class Agent extends Board{    
    private static boolean arrow;
    private static boolean backmove;
    private static boolean gotGold;

    private static int atlocationX;
    private static int atlocationY;
    private static int faceposition; 
    private static int pathcounter;

    public boolean temporaryGold;
    public boolean temporaryWumpus;
    public boolean temporaryStench;
    public boolean temporaryBreeze;
    public boolean temporaryPit;

    int agentgui = 0;
    int label = 0;

    Block blockstorage[][] = new Block[4][4];
    KnowledgeBase kb = new KnowledgeBase();

    public Agent() {
        super();
    }

    public void Agent(){
        Agent.arrow = true;
        Agent.faceposition = 2;
        Agent.atlocationX = 0;
        Agent.atlocationY = 0;
        Agent.backmove = false;
        Agent.gotGold = false;
        Agent.pathcounter = 1;
    }
}

问题在于,当我尝试添加

Agent agent = new Agent();

在我的一些其他类中,例如:

public class Board {
    Agent agent = new Agent();
}

它会返回错误:

  
    

线程“AWT-EventQueue-0”中的异常java.lang.StackOverflowError

  

我也在我的主要尝试过但仍然一样。

导致此异常的原因是什么?

3 个答案:

答案 0 :(得分:5)

您正在使用间接递归调用进行无限循环。

构建Board对象需要Agent个对象,反之亦然

答案 1 :(得分:1)

问题是您的Agent类扩展Board

public class Agent extends Board

Agent类的构造函数中,您正在调用super()构造函数,该构造函数调用Board类构造函数

public Agent() {
    super();
 }

最后,您的Board课程会创建一个Agent

的对象
public class Board {
 Agent agent = new Agent();

导致无限循环导致:Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError

编辑:评论中的问题答案
根据您的代理类

public class Agent{    
private static boolean arrow;
private static boolean backmove;
private static boolean gotGold;

private static int atlocationX;
private static int atlocationY;
private static int faceposition; 
private static int pathcounter;

public boolean temporaryGold;
public boolean temporaryWumpus;
public boolean temporaryStench;
public boolean temporaryBreeze;
public boolean temporaryPit;

int agentgui = 0;
int label = 0;

Block blockstorage[][] = new Block[4][4];
KnowledgeBase kb = new KnowledgeBase();

public void Agent(){
    Agent.arrow = true;
    Agent.faceposition = 2;
    Agent.atlocationX = 0;
    Agent.atlocationY = 0;
    Agent.backmove = false;
    Agent.gotGold = false;
    Agent.pathcounter = 1;
 }
}

您的董事会成员应该如下

public class Board {
 Agent agent = new Agent();
 // Now you can call your method of Agent class like following 
 agent.Agent()
}

答案 2 :(得分:0)

代理人扩展董事会,董事会需要代理人。虚拟机花费无限时间尝试完成该任务。

这就像一张纸,两边写着“翻过来”。你花了无数时间试着遵循指示。

此外,请先考虑回答StackOverflow上的一些问题,然后再询问“找我问题”类型的问题。