如何从Java中私有的另一个类访问数组?

时间:2018-11-15 19:13:43

标签: java arrays class if-statement private

我在创建原始象棋游戏的项目中设置了2个类。我正在尝试从另一个类访问数组,但是它是私有的。我将如何从另一个类引用和访问该数组?以下是相关代码的各个部分:

private static final char FREE         = '.';
private static final char WHITEROOK    = '♖';
private static final char BLACKROOK    = '♜';
private static final char WHITEBISHOP  = '♗';
private static final char BLACKBISHOP  = '♝';

private int boardsize;
private char[][] board;

public Board() {
    this.boardsize = DEFAULT_SIZE;

    board = new char[boardsize][boardsize];

    // Clear all playable fields
    for(int x=0; x<boardsize; x++)
        for(int y=0; y<boardsize; y++)
            board[x][y] = FREE;

    // Placing Initial Pieces on the board
    board[2][0] = WHITEBISHOP;
    board[5][0] = WHITEBISHOP;
    board[2][7] = BLACKBISHOP;
    board[5][7] = BLACKBISHOP;
    board[0][0] = WHITEROOK;
    board[7][0] = WHITEROOK;
    board[0][7] = BLACKROOK;
    board[7][7] = BLACKROOK;
}

这是我要访问的板阵列,用于与if语句中的其他阵列进行比较。

谢谢!

3 个答案:

答案 0 :(得分:0)

最好的解决方案可能是不允许其他任何类直接访问该数组,而只能让Board类自己这样做。

这可以通过创建公共方法来移动一件作品,印刷木板等来完成

这是一个非常简化的示例

public void move(int fromX, int fromY, int toX, int toY {
    char piece = board[fromX][fromY];
    board[toX][toY] = piece;
} 

然后在另一个类中的用法是

Board b = new Board();
b.move(4,1,4,3);

您说您想将数组与其他数组进行比较,但是如果它是由Board类处理的,那就更好了

public int compareWith(char[][] otherArray) {
    int result = 0;
    //compare
    return result;
}

甚至更好,如果您要比较两个板,那就应该是

public int compareWith(Board otherBoard) {
    int result = 0;
    //compare
    return result;
}

答案 1 :(得分:-1)

欢迎来到!

对此的传统解决方案是公开该领域:

public char[][] board;

或更可能更安全,更常见的方法是,创建一种吸气方法:

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

然后,在另一个类中,您可以创建一个Board并使用getter访问其board

Board myBoard = new Board();
char[][] boardArray = myBoard.getBoard();
//use the array:
System.out.println(boardArray[0][2]);

答案 2 :(得分:-1)

尝试创建返回数组或更改其内部的公共方法

示例

public void EditArray(int index1, int index2, char value){ board[index1][index2] = value; }

直接获取数组的值将不起作用,无论如何,您都必须编写方法(对不起,我的英语)