Should I use global variables or pass variables in java?

I am creating a sim game based on the 2nd level. I have a 2d array of gridSquares that many classes and methods access and change. Do I have to pass a gridSquares 2d array every time or make it global? What is the practice?

I thought it would be possible to create a class that simply contains a set of variables that could extend all classes? Is this a good or bad idea / not a good practice?

I'm still pretty new to java, so I'm still learning a lot!

Thanks in advance.

Rel

+3
source share
5 answers

. Java - - . . 2D-; Board. , 2D-.

, :

public class Board
{
    // This is what you're passing around now; Board hides it.
    // Square is the abstraction of a position on the Board
    private Square[][] grid;

    public Board(int nRows, int nCols)        
    {
       this.grid = new Square[nRows][];
       for (int i = 0; i < this.grid[i].length; ++i)
       {
           this.grid[i] = new Square[nCols];
       }
    }

    // Now add methods for adding Pieces to the Board, rules for moving them, etc.
} 
+7

-.

, , , .

+4

, - "2d- gridSquares", singleton, Essentailly .

, , , , (, ).

+2

, grid- (A) , A (import static A;). , A, .

. , . . , .

+1

, , , , GridSquaresAcessor. . , , , .

, GridSquaresAcessor .

, ...

, , 2D- .

+1

Source: https://habr.com/ru/post/1707100/


All Articles