我如何在具有不同构造函数的方法中创建给定对象类型的对象
how I create objects of the given object type in a method with different constructors
我的问题:我想在一个方法中创建对象,该方法接收我要创建的对象以及我想要的数量。而且每个人在构造函数中接收不同的参数
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));
}
}
}
在摘要中 class Tile 我这样写:
public abstract GameTile getNewTile(int x, int y);
在我的瓷砖中:
@Override
public Tile getNewTile(int x, int y) {
return new Floor(x, y); //if the tile is floor
}
当我想创建地砖时:
addTiles(0, 0, 12, 20, new Floor(0, 0));
我的方法看起来像:
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()));
}
}
}
如果您在没有创建此抽象方法的情况下找到了解决方案,请将其记录下来。谢谢!
我的问题:我想在一个方法中创建对象,该方法接收我要创建的对象以及我想要的数量。而且每个人在构造函数中接收不同的参数
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));
}
}
}
在摘要中 class Tile 我这样写:
public abstract GameTile getNewTile(int x, int y);
在我的瓷砖中:
@Override
public Tile getNewTile(int x, int y) {
return new Floor(x, y); //if the tile is floor
}
当我想创建地砖时:
addTiles(0, 0, 12, 20, new Floor(0, 0));
我的方法看起来像:
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()));
}
}
}
如果您在没有创建此抽象方法的情况下找到了解决方案,请将其记录下来。谢谢!