问题
So I have a method that looks like this:
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];
}
So I want to use the variables x, numRows and numCols in other methods however numRows and numCols needs the String textmaze which must be passed in as a parameter and the main method where this method is called is in another class which I'm not allowed to modify. So how can I use those variables in other methods?
回答1:
Since Maze
is a constructor, and you want to use the variables in other parts of the class, you should make the variables instance fields instead, for example...
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 will allow you to access the variables from within THIS (Maze
) classes context.
Depending on what you want to do, you could also provide accessors for the fields to allow child classes access to them (using protected
to prevent other classes from outside the package from accessing them or public
if you want other classes to access them)...
public int getNumRows() {
return numRows;
}
Take a look at Understanding Class Members and Controlling Access to Members of a Class for more details
来源:https://stackoverflow.com/questions/28822056/how-do-i-use-variables-declared-in-one-method-in-another-method