'Create a board made of Cells able host a Generic value

I'm working on a project(a game) which will have a board to play on.

I want to make this board as generic as possible in order to be able to re-use the code for a possible other game.

public class Board {
    private int rows;
    private int cols;
    private Box[][] board;

    public Board(int rows, int cols){
        Box[][] board = new Box[rows][cols];
        for (int row = 0; row < this.rows; row++){
            for (int col = 0; col < this.cols; col++){
                board[row][col] = new Box();
            }
        }
    }

    public int getCols(){return this.cols;}
    public int getRows(){return this.rows;}

    public Piece getContentAtPos(int row, int col){
        return board[row][col].getContent();
    }
}

This is the Board class. The problem here is that I have to return a Piece object with the getContentAtPos() method because the Box (Cell) class is like this:

public class Box {
    private boolean empty;
    private Piece content;

    public Box(){
        empty = true;
    }

    public Box(Piece piece){
        empty = false;
        this.content = piece;
    }

    public boolean isEmpty(){
        return empty;
    }

    public Piece getContent(){
        if (!empty) {
            return content;
        } else {
            return null;
        }
    }
}

Whereas, the ideal for me would be the class Box to be able to host any type of object and return this generic object with getContentAtPos() via the Box getContent() method.

My generic Box class.

public class Box<T>{
    private boolean empty;
    private T content;

    public Box(){
        empty = true;
    }

    public Box(T content){
        this.content = content;
        empty = false;
    }

    public boolean isEmpty(){
        return empty;
    }

    public T getContent(){
        if (!isEmpty()){
            return content;
        }
        return null;
    }

    public T setContent(Object content){
        this.content = content;
    }
}

But what do I need to change in the Board class?

What return value shall I put there?



Solution 1:[1]

You should create interface that every class you will return in the future will implement. This way you will be sure that return type will implement interface and have defined behaviour.

    public interface ReturnableBox { 
          public boolean isEmpty();
    }
    public class Board {

       private int rows;
       private int cols;
       private ReturnableBox [][] board;
   }
   public class Box implements ReturnableBox {
   //...
   }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Milan