我有一個魔方課,內容如下:public class Rubik{ private int[][][] grid; protected Face[] cube; protected Face up; protected Face left; protected Face front; protected Face right; protected Face down; protected Face back; private static String dots = "......"; private String output; //Constructor public Rubik(int[][][] grid){ int[][][] copy_grid = new int[6][3][3]; for (int k = 0; k < 6; k++){ for (int i = 0; i < 3; i++){ for (int j = 0; j < 3; j++) copy_grid[k][i][j] = grid[k][i][j]; } } this.grid = copy_grid; this.up = new Face(grid[0]); this.left = new Face(grid[1]); this.front = new Face(grid[2]); this.right = new Face(grid[3]); this.down = new Face(grid[4]); this.back = new Face(grid[5]); this.cube = new Face[]{this.up, this.left, this.front, this.right, this.down, this.back}; }我正在嘗試創(chuàng)建一個擴展 Rubik 的 RubikRight 類,并且 RubikRight 的定向方式使得原始 Rubik 的右面現在面向前方。這就是我為 RubikRight 定義構造函數的方式:public class RubikRight extends Rubik{ //Constructor public RubikRight(int[][][] grid){ int[][][] copy_grid = new int[6][3][3]; for (int k = 0; k < 6; k++){ for (int i = 0; i < 3; i++){ for (int j = 0; j < 3; j++) copy_grid[k][i][j] = grid[k][i][j]; } } this.grid = copy_grid; this.up = new Face(grid[0]); this.left = new Face(grid[2]); this.front = new Face(grid[3]); this.right = new Face(grid[5]); this.down = new Face(grid[4]); this.back = new Face(grid[1]); this.cube = new Face[]{this.up, this.left, this.front, this.right, this.down, this.back}; }我可以知道為什么我似乎無法這樣定義 RubikRight 嗎?
2 回答

繁星淼淼
TA貢獻1775條經驗 獲得超11個贊
每當實例化子類對象時,都會隱式調用父類默認構造函數。因此,當您RubikRight通過調用它來實例化時,會從 RubikRight 的構造函數內部new RubikRight(int[][][])隱式調用。super()因此出現錯誤:
required: int[][][] // what you have in Rubik class, note that you don't have the default constructor
found: no arguments // super(/* no argument */) called implicitly
要消除錯誤,您有兩種選擇:
要么super(grid)從RubikRight構造函數顯式調用。
或者,在(基)類中實現默認構造函數Rubik。

紫衣仙女
TA貢獻1839條經驗 獲得超15個贊
您沒有調用父類的構造函數。
這里你可以做的是,重載父類中的構造函數。創(chuàng)建默認構造函數(無參數構造函數)并使其受保護。
public class Rubik{
...
protected Rubik() {
}
}
這應該可以解決你的問題。
添加回答
舉報
0/150
提交
取消