1

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));
            }
        }
    }
Jean_K
  • 51
  • 7
  • 2
    Builder Pattern will help you to solve avoid Telescoping Constructor or multiple constructors. Quaoting Effective Java by Joshua Bloch: "Traditionally, programmers have used the telescoping constructor pattern, in which you provide a constructor with only the required parameters, another with a single optional parameter, a third with two optional parameters, and so on, culminating in a constructor with all the optional parameters." More about Builder Pattern in Effective Java can be found here at Stackoverflow: https://stackoverflow.com/questions/5007355/builder-pattern-in-effective-java – DigitShifter Aug 29 '20 at 17:48

1 Answers1

0

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 !

Jean_K
  • 51
  • 7