Search code examples
javaobjectmethodsbuilder

how I create objects of the given object type in a method with different constructors


My problem: I want to create objects in a method that receives the object I want to create and how many I want. Also each one receives different arguments in the constructor

    public void addTiles(int x, int y, int rows, int columns, Object tile){
        for(int i=0; i<rows; i++){
            for(int j=0; j<columns; j++){
                //Attempts
                //add(new Class<tile.getClass()>(x+j*64,y+i*64));
                //add(tile.getClass().newInstance().setLocation(x+j*64,y+i*64));
                //add(((GameTile)tile.clone()).setLocation(x+j*64,y+i*64));
            }
        }
    }

Solution

  • In the abstract class Tile i write this:

    public abstract GameTile getNewTile(int x, int y);
    

    In my tiles:

    @Override
    public Tile getNewTile(int x, int y) {
        return new Floor(x, y); //if the tile is floor
    }
    

    When i want to create Floor tiles:

    addTiles(0, 0, 12, 20, new Floor(0, 0));
    

    where my method looks like:

    public void addTiles(int x, int y, int filas, int columnas, Tile tile){
        for(int i=0; i<filas; i++){
            for(int j=0; j<columnas; j++){
                add(tile.getNewTile(x+j*tile.getWidth(),y+i*tile.getHeight()));
            }
        }
    }
    

    If you find a solution without creating this abstract method write it down please. Thanks !