简体   繁体   中英

How do I access a certain element of an object if you are in another class?

I have a class that contains a 2D char[][] array that makes a connect four board. Each of these elements in the char array holds either an 'X' or 'O'.

Right now I am trying to get the contents of this board while I am in another class so for example,

public class Connect4
{
 private char[][] board;
}



public NewClass
{
 private Connect4 board;
 board = new Connect4(sizeX, sizeY);

 board..... <-- how do I access the char contents of the Connect4 object if I am in the NewClass?
}

Thanks

You cannot access board because you made it private . If you meant for it to be publicly accessible, you have two options.

Option 1 - Accessor Methods

Keep the board field private and make it accessible through an accessor (aka setter) method, inside of your Connect4 class.

public void setBoard(int row, int col, char player) throws SlotTakenException {
    if(board[row][col] == 'A')
        throw new SlotTakenException("A player has already put a piece here.");
    board[row][col] = player;
}

Notice that I threw a custom SlotTakenException . If you don't know about Exceptions yet, you can learn about them here . You can also find out more about accessor/setter/mutator methods here .

Option 2 - Public Fields

If you do not care who touches your board, you can simply make the board itself public . A complicated game board should probably never be public, as it could lead to players making moves in the same slot. Some purists will argue that using the public modifier in front of a field is never a good idea. Should you decide to ignore their warning:

public char[][] board;

Either method will work, but the first method lets you place responsibility on the Board class to maintain its own consistent state, which is the more acceptable method.

First off, you should ignore the recommendations given to make the data public.

You will want to give your Connect4 class public methods that allow other classes controlled access to its data. This means that you can possibly allow outside classes to mutate the data of Connect4, but only if it does so in a logical way. For instance, it would make no sense to allow an outside class to try to change the state of an array item that is out of bounds, and your setter methods can control this. This is one advantage of encapsulating your data, of hiding your class's data as much as possible, and allowing only controlled and moniterable access.


For example,

public class Connect4 {
 private char[][] board;
 private int rows;
 private int cols;

 public Connect4(int rows, int cols) {
   board = new char[rows][cols]
   this.rows = rows;
   this.cols = cols;
 }

 public void setBoardCell(int row, int col, char value) throws Connect4Exception {
   // first check value of row and col and if not valid, throw exception
   // if board is a bound field, then fire property change notification here
   board[row][col] = value; 
 }

 public char getBoardCell(int row, int col) {
   return board[row][col];
 }
}

And...

class Connect4Exception extends Exception {
  // default constructor
  // String constructor
} 

That's what private members are for. You can only access them from the class they are declared in. Try to give class Connect4 some methods to deal with its data so it must not make its internals public. That's an important concept of object oriented programming.

A best practice is to make a private method called getter in Connect4 class, that will make board field indirectly accessible. This way, you can clearly define the behaviour, that Connect4 class will allow and which field will it make accessible and how.

public class Connect4 {
    private char[][] board;

    public char[][] getBoard() {
        return board;
    }
}

Then in NewClass you call board.getBoard() to get access to the field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM