0

I'm creating a small chess game using JButtons as each individual tile of the chessboard. I then give each tile (64 in total) an action listener, using the following code:

for (int y = 0; y < chessBoardColumns; y++) {
    for (int x = 0; x < chessBoardRows; x++) {
        JButton square = new JButton();
        ActionListener squareListener = new ChessSquareListener(this);
        chessBoardSquares[x][y] = square;
        chessBoardSquares[x][y].addActionListener(squareListener);
    }
}

The action listener is in a separate package, and looks like the following:

public class ChessSquareListener implements ActionListener {
    private ChessGame game;

    public ChessSquareListener(ChessGame game) {
        this.game = game;
    }

    public void actionPerformed(ActionEvent e) {
        game.doSomething();
    }
}

As you can see, i'm passing the instance of the entire game to each squares listener. Would this be creating 64 copies of the game for each listener, or does it just pass a reference to the game instance?

gillepsi
  • 9
  • 2

1 Answers1

1

You may find this answer useful: Is Java "pass-by-reference" or "pass-by-value"?

Anyways, because of the fact that every instance of a class is actually a pointer in Java, the answer to your question is that it just passes a reference (pointer) to the game instance (as stated by the comment of prasad). Thus, Java does not create a copy, which means on the other hand that if the listeners would manipulate the passed "instance" (this), the manipulation would effect the one instance, which is used by all the 64 listeners.

If you need more insights, just let me know :).

Community
  • 1
  • 1
Philipp
  • 1,289
  • 1
  • 16
  • 37