子class 调用父class 递归java

Sub class call parent class recursion java

大家新年快乐:-) 我需要你的帮助来理解我的错误。

我创建了板 class 和扩展板 class 的单元 class,并且在板 class 中我还有一个单元数组。 当我 运行 我的代码出现 java.lang.WhosebugError 异常时。

棋盘class:

Cell boardGame[][] = new Cell[8][8];

public Board() {
    /*
     * for (int i = 0; i < board.length; i++) { for (int j = 0; j <
     * board[i].length; j++) { board[i][j] = "-"; }
     */
    reorder();
    printBoard();
}

public void reorder() {
    for (int i = 0; i < 8; i++) {
        boardGame[1][i] = new Cell((new Pawn(ChessPiece.PAWN, Color.BLACK)), 1, i);
        boardGame[6][i] = new Cell((new Pawn(ChessPiece.PAWN, Color.WHITE)), 6, i);
    } 
{...}

单元格 class:

public Cell(int xPosition, int yPosition) {
        position = new MoveSet(xPosition, yPosition);
        color = null;
        display = null;
    }

    public Cell(Soldier soldier, int xPosition, int yPosition) {
        this(xPosition, yPosition);
        this.soldier = soldier;
        setRoleMark();
    }

{...}

当我尝试调试时,我注意到我的 Cell 构造函数转到 Board 构造函数并再次 运行 reorder(),然后它创建另一个 Cell 构造函数转到 Board 构造函数和 运行重新订购...

我意识到这是一个糟糕的设计,因为我的 Cell class 不需要 Board class 的任何东西,但我想了解为什么会这样。 我从来没有调用过 super,所以为什么我的单元格 class 调用电路板构造函数?

我的猜测是每个 Cell 都试图从它的 super class 中创建 Cell boardGame[][] = new Cell[8][8](因为 sub class 得到了 super 变量吗?)所以它基本上试图创建自己.

但是我不确定,你能批准给我吗?

谢谢, 或者

您收到此错误是因为 Java 隐式调用 super() 作为构造函数的第一个操作,如果您自己不这样做的话。

If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body implicitly begins with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments.

完整参考见此处:http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.8.5


作为 side-note,除此之外让 Cell 扩展 Board 是一个坏主意,您可能希望将您的开发板移至静态工厂方法中,并且让他 Board() 构造函数几乎是空的。这样你就永远不会 运行 进入这些 hidden side-effects.

在 java 中,任何子类构造必须在超类构造函数调用之后,如果您没有显式调用超级构造函数 java 默认情况下通过默认构造函数构造超类。