繁体   English   中英

我如何在具有不同构造函数的方法中创建给定对象类型的对象

[英]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));
            }
        }
    }

在抽象类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()));
        }
    }
}

如果您在不创建此抽象方法的情况下找到解决方案,请写下。 谢谢 !

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM