Home > database >  Private and final methods
Private and final methods

Time:04-09

I am trying to get a better understanding of private and public methods. I am trying to make a private method called GRID_SIZE and let that equal the length(m) of my grid, however, I am getting a message saying that it cannot be resolved into a variable. My understanding is that if a method is private only the class can access it and if a method is public any class can enter. So I am confused as to why I can't take a variable from the public method to a private method.

public class trial1 {
    

    private static final int GRID_SIZE = m; 
    
    public static void main(String[] args) {
            
            int m = 8; 
            char[][] grid = new char[m][m];
            
            for (int i=0; i<grid.length; i  ) {
                for(int j = 0; j<grid[i].length; j  ) {
                    grid[i][j] = '*';
                    StdOut.print(grid[i][j]);
                }
                
            StdOut.println();
                
            }
            
    }
}

CodePudding user response:

You're creating a static field, not a method. The visibility is not relevant to the question.

Static (class) variables simply cannot be set before the class is initialized; there is no m until the main method is executed (after the class is instantiated by the JVM). Plus, you've made the field final, so it cannot be modified within the main method, anyway.

Perhaps you want this?

public class Trial1 {

    private static final int GRID_SIZE = 8; 

    public static void main(String[] args) {
        char[][] grid = new char[GRID_SIZE][GRID_SIZE];

CodePudding user response:

Your problem here is around scope.

Variables defined within a method are only visible within that method. So in your code the variable m is only accessible by code inside the main class.

GRID_SIZE is a private static field (not a method) and that means it is accessible by all code within the class.

If you want GRID_SIZE to be assigned a value defined in method scope (e.g. m) then you need to remove the final from GRID_SIZE and set it from within the main method.

Something like:

public class Trial1 {

private static int GRID_SIZE ; 

    public static void main(String[] args) {
        
        int m = 8; 
        GRID_SIZE = m;
        char[][] grid = new char[m][m];
        
        for (int i=0; i<grid.length; i  ) {
            for(int j = 0; j<grid[i].length; j  ) {
                grid[i][j] = '*';
                StdOut.print(grid[i][j]);
            }
            
            StdOut.println();
            
        }
        
    }
}

Please note this is just an example of how to change GRID_SIZE. If you just want GRID_SIZE to always be a particular value then as the previous answer states you could just set it directly to 8.

  • Related