How do I use variables declared in one method, in another method.

后端 未结 1 1705
南方客
南方客 2021-01-24 02:02

So I have a method that looks like this:

public Maze(String[] textmaze, int startRow, int startCol, int finishRow, int finishCol){
    int numRows = textmaze.len         


        
1条回答
  •  鱼传尺愫
    2021-01-24 02:47

    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

    0 讨论(0)
提交回复
热议问题