如何实例化一个调用自身另一个实例化的类?

3

我想编写魔方代码,每个面需要六个Face类。在这个类中,为了正确移动魔方,我需要访问其四周的面,因此我试图在一个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);
        }
    }
}
3个回答

1
你可以在没有相邻面的情况下初始化一个Face。然后,在所有它们都初始化后,通过setters定义它们之间的关系。
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;
  }

}

1
我通常会添加一个初始化函数,该函数在所有对象实例化后使用,并将需要其他实例的代码移动到该函数中。这样,在调用代码时,您已经拥有有效的引用:
    // Instantiate the objects:
    white = new Face(Color.WHITE);
    yellow = new Face(Color.YELLOW);
    red = new Face(Color.RED);
    orange = new Face(Color.ORANGE);
    blue = new Face(Color.BLUE);
    green = new Face(Color.GREEN);
    // Initialize the objects:
    white.intitializeFace(red, blue, green, orange);
    yellow.intitializeFace(orange, blue, green, red);
    red.intitializeFace(yellow, blue, green, white);
    orange.intitializeFace(white, blue, green, yellow);
    blue.intitializeFace(red, yellow, white, orange);
    green.intitializeFace(red, white, yellow, orange);

    front = yellow;


    public Face(Color c) {
        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);
            }
        }
    }
    public void intitializeFace(Face t, Face l, Face r, Face b) {
        top = t;
        left = l;
        right = r;
        bottom = b;
    }

0

这个例子不会起作用,因为在实例化之前不能引用对象,除非它们已经声明了一些状态。

话虽如此,如果您有另一个对象,比如说Block,其中包含4个面对象,那么这将解决您的问题。一个面可以由颜色组成,而Block可以管理所有逻辑。

enum Face {
    WHITE(Color.WHITE),
    RED(Color.RED),
    BLUE(Color.BLUE)
    // other elements
    // constructor
    // getters
}

class Block {

    // class members

    // cells

    public Block(Face top, Face left, Face right, Face bottom) {
        // assignment
    }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接