Search code examples
javamethodssubroutine

Java - Defining a Method/function/subroutine within a class method


So basically the problem is that I have segment of code that needs to be re-used with very slight variations through out in a java method.

This section of code also needs access to a variable only defined within the class method.

I did a search, but found no way that I can add a subroutine within a method. I thought about adding a local class, but it seems you can't use static methods with these, which is what I really need.

If it helps at all, my goal is to initialise a gameboard, that basically consists of:

GameSquare[][] board = new GameSquare[15][15];

and for each call:

board[a][b] = new GameSquare(params);

there should be a corresponding call for:

board[b][a] = new GameSquare(params);
board[15-a][15-b] = new GameSquare(params);
board[15-b][15-a] = new GameSquare(params);

Ie any special square needs to mirrored across the other four corners.

I'm hoping to have all these included within a single method. If there were a way to have an method within a method, I could just have:

method( int a, int b, otherparams passed to GameSquare constructor){
  //initialise those 4 squares.
}

But, so far I have not found such a way of doing this.

Cheers.


Solution

  • Since it's an array, how about just passing the array as a parameter to the method? Except for primitives (int, float, etc.), parameters in Java are passed by reference so you are still modifying the same array.

    method(GameSquare[][] board, int a, int b, otherparams passed to GameSquare constructor){
        board[a][b] = new GameSquare(params)
        board[b][a] = new GameSquare(params)
        board[15-a][15-b] = new GameSquare(params)
        board[15-b][15-a] = new GameSquare(params)
    }
    

    Using it:

    GameSquare[][] board = new GameSquare[15][15];
    method(board,a,b,params);