What is the best way to initialise static members before constructing objects in Java?

I am currently in the process of refactoring the code I wrote for a text/console version of the Mastermind board game. I am a bit stuck with how to best approach improving this section my GameLogic class.

public GameLogic(GameSettings gameSettings)
    // ..other stuff..

    // initialise static members

    // InputBoard and OutputBoard extends the abstract class Board
    inputBoard = new InputBoard();
    outputBoard = new OutputBoard();

What I am trying to do is set the static values of totalRows and totalColumns in the Board class BEFORE constructing the inputBoard and outputBoard objects. The reason why I want to do this is because I need to have these values present when constructing instances extending Board (an abstract class). The reason why I am making these values static is because they should be the same across all instances extending from Board and so that I can do something like Board.getTotalColumns() throughout the application.

The reason why I think this is suspiciously bad is because it would be possible to declare inputBoard or outputBoard without first setting the static member variables and of course it would also be possible to accidentally set the values of the static member later on to any arbitrary value.

Another approach I thought of was to make the getters in GameSettings public and static so that I could do something like this instead:

public abstract class Board 
    private static final int totalColumns = GameSettings.getCodeLength();
    private static final int totalRows = GameSettings.getNumOfGuesses();

    // other stuff...

This would allow me to avoid using setters and the problems associated with using them as listed above. But wouldn’t this defeat the purpose of instantiating a GameSettings object?

What do you think are better alternatives to approach this?


I am not an expert on design pattern. I would try something like below –


abstract class Board {
    private final GameSettings gameSettings;

    Board(GameSettings gameSettings) {
        this.gameSettings = gameSettings;
    public int getTotalColumns() {
        return gameSettings.getCodeLength();
    public int getTotalRows() {
        return gameSettings.getNumOfGuesses();

    //Other abstract methods

InputBoards .java

class InputBoards extends Board {
    InputBoards(GameSettings gameSettings) {

OutputBoards .java

class OutputBoards extends Board {
    OutputBoards(GameSettings gameSettings) {

GameSettings .java

class GameSettings {
    public int getCodeLength() {
        //return your value;
    public int getNumOfGuesses() {
        //return your value;

Now I would do –

public GameLogic(GameSettings gameSettings) {
    inputBoard = new InputBoard(gameSettings);
    outputBoard = new OutputBoard(gameSettings);

Leave a Reply

Your email address will not be published. Required fields are marked *