Search code examples
javastaticprogram-entry-point

Using classes in static main method


So I'm writing a mini-board game program in Java.

The program is going to read in standard input and construct a game as directed in the input.

To help stay organized and progress my oo java skills, I am using a Cell class to act as a cell in a nxn game.

For the board game, I need to have it all in one file, and it must run from static void main.

Here's what my Cell class looks like

public class Cell{
      public int x;
      public int y;
      .
      .
      .
 }

I want to read the input, and assign values to each cell and then add the cells to a list such as ArrayList allCells. However, I can not the use it in a static context.

I understand that static is a single instance, so I'm confused how I would go about doing this. Is there anyway I can use a class-based system to solve this problem. Each cell is it's own individual object, so making it stat wouldn't work.

Any sort-of explanation or alternative would be amazing! Hope I was clear enough in my description.


Solution

  • The best approach would be to make Cell a top-level class in its own file, but you've indicated that you need everything in a single file. So I'll answer with that constraint in mind.

    You need to declare the Cell class itself to be static in order to use it in a static context. For instance:

    public class Game {
        public static class Cell { // doesn't really need to be public
            ...
        }
    
        public static void main(String[] args) {
            Cell c1 = new Cell();
            Cell c2 = new Cell();
            ...
        }
    }
    

    Without the static modifier for the Cell class, you will get a compiler error when calling new Cell() inside main() (which I'm guessing is basically the problem you are having).

    An alternative is to modify the Cell class to be non-public. Then you can make it a top-level class in the same file as your game class:

    public class Game {
        public static void main(String[] args) {
            Cell c1 = new Cell();
            Cell c2 = new Cell();
            ...
        }
    }
    
    class Cell {
        ...
    }
    

    Yet another alternative would be to make Cell a local class in the main() method:

    public class Game {
        public static void main(String[] args) {
            class Cell {
                ...
            }
            Cell c1 = new Cell();
            Cell c2 = new Cell();
            ...
        }
    }
    

    However, then you would only be able to use the Cell class in the main() method itself; you could not take advantage of the Cell structure in any other methods of your game.