Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you instantiate a class that calls another instantiation of itself?

I am trying to code a rubiks cube and I want to have six Face classes for each face of the cube. In the class I need access to the faces on all four sides of it in order to move the cube correctly so I tried to have four other Face objects in the constructor of a Face. I am wondering if this instantiation would work. Here is how I did it(The first chunk of code is in the main class and the second chunk is from the Face class):

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);
        }
    }
}
like image 608
Mizt1c Avatar asked Nov 19 '25 09:11

Mizt1c


1 Answers

You can initialise a Face without neighbouring faces first. Then, after all of them are initialised, you define relationships between them by 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;
  }

}
like image 148
Andrew Tobilko Avatar answered Nov 20 '25 22:11

Andrew Tobilko