Does Java have a const reference equivalent?

c++, constants, java

Solution

Define the variable as `protected`, so that if the unit test is in the same package, it can access it.

However, I would just add a public method `getPiece(int row, int col)` that returns the piece on that square (or null if there's no piece there). It's likely you'll need a method like that anyway, and you could use it in your tests.

Problem

Here's a snippet of code: ``` //Game board is made up of Squares. A player can place GamePieces on a Square. public class CheckersBoard { public boolean PlaceGamePiece(GamePiece gamePiece, int nRow, int nColumn) { return m_theGameBoard[nRow][nColumn].PlaceGamePiece(gamePiece); } private Square[][] m_theGameBoard; } ``` Let say I'm testing the PlaceGamePiece method (using junit) and I need to access the m_theGameBoard so I can look at it and verify the GamePiece was placed on the correct Square and has the correct data. In C++ I'd either make the test class a friend so it can access the private member m_theGameBoard, or I'd have a function that returns a const GameBoard that cannot be modified (because it's const): ``` const GameBoard& GetGameBoard() const { return m_theGameBoard; } ``` Now I can do what ever checking I want to do on the game board, but I can't modify the game board because it's const. Java doesn't support returning const references or friend classes. So my question is what is the standard Java way of doing this?? Do I have to just provide a bunch of get accessors that allow me check the data on the `Square`? UPDATE: I ended up writing a GetPiece method as Kaleb Brasee suggested. ``` public GamePiece GetGamePiece(Point pt) { return new GamePiece(m_theGameBoard[pt.GetRow()][pt.GetColumn()]); } ``` Notice I create a new GamePiece object and return that. I'm not returning the GameBoards internal reference, therefore no one can modify the gameboard because they only have a copy! Nice! Thanks for the help guys, some really good advice. FYI: I keep changing the names of the objects when I post them on here, sorry if that confused anyone.

Original source