如何在另一种方法中使用在一个方法中声明的变量。

时间:2015-03-03 00:39:02

标签: java class variables methods

所以我有一个看起来像这样的方法:

public Maze(String[] textmaze, int startRow, int startCol, int finishRow, int finishCol){
    int numRows = textmaze.length;
    int numCols = textmaze[0].length;
    int [][] x = new int[numRows][numCols];
    }

所以我想在其他方法中使用变量x,numRows和numCols,但是numRows和numCols需要String textmaze,它必须作为参数传入,并且调用此方法的main方法在另一个类中我和# 39; m不允许修改。那么如何在其他方法中使用这些变量呢?

1 个答案:

答案 0 :(得分:1)

由于Maze是构造函数,并且您希望在类的其他部分中使用变量,因此您应该改为使用变量实例字段,例如......

private int numRows;
private int numCols;
private int [][] x;

public Maze(String[] textmaze, int startRow, int startCol, int finishRow, int finishCol){
    numRows = textmaze.length;
    numCols = textmaze[0].length;
    x = new int[numRows][numCols];
}

这将允许您从THIS(Maze)类上下文中访问变量。

根据您要执行的操作,您还可以为字段提供访问器以允许子类访问它们(使用protected来防止包外的其他类访问它们或public如果你想让其他课程访问它们......)

public int getNumRows() {
    return numRows;
}

请查看Understanding Class MembersControlling Access to Members of a Class了解详情