我正在尝试编写一个 rubiks 立方体代码,我希望立方体的每个面都有六个面类。在类中,我需要访问其所有四个面的面,以便正确移动立方体,因此我尝试在 Face 的构造函数中使用其他四个 Face 对象。我想知道这个实例化是否可行。这是我的做法(第一段代码在主类中,第二段代码来自 Face 类):
white = new Face(red, blue, green, orange, Color.WHITE);
yellow = new Face(orange, blue, green, red, Color.YELLOW);
red = new Face(yellow, blue, green, white, Color.RED);
orange = new Face(white, blue, green, yellow, Color.ORANGE);
blue = new Face(red, yellow, white, orange, Color.BLUE);
green = new Face(red, white, yellow, orange, Color.GREEN);
front = yellow;
public Face top, left, right, bottom;
public Cell[][] cells;
public Face(Face t, Face l, Face r, Face b, Color c) {
top = t;
left = l;
right = r;
bottom = b;
cells = new Cell[3][3];
for(int row = 0; row < 3; row++) {
for(int col = 0; col < 3; col++) {
cells[row][col] = new Cell(c);
}
}
}
最佳答案
您可以先初始化没有相邻面孔的 Face
。然后,在所有这些都初始化之后,您可以通过 setter 定义它们之间的关系。
class Face {
Face white = new Face(Color.WHITE);
Face yellow = new Face(Color.YELLOW);
{
white.setRight(yellow);
yellow.setLeft(white);
}
public Face top, left, right, bottom;
public Cell[][] cells;
public Face(Color c) {
// only cells init
}
public void setLeft(Face left) {
this.left = left;
}
public void setRight(Face right) {
this.right = right;
}
}
关于java - 你如何实例化一个调用自身的另一个实例化的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61253877/