我试图首先填充一个通用对象列表,然后实例化它们,并在实例化它们时,指定每个对象是哪个对象。
我正在处理的用例是读取数据文件并构建具有各种可交互对象的地图。每个对象的可交互类型存储在它自己的数据文件中,该文件来自地图的数据文件。一些代码例如:
在阅读地图时:
if ((char)map[i][j] == '*')
mapObjects.add(new MapObject());
之后:
for (int i = 0 ; i < mapObjects.size() ; i++)
mapObjects.set (i, new MapObject(in.readLine()));
//in.readLine gives the path for the file
在 MapObject 的构造函数中:
public MapObject (String in){
try{
BufferedReader br = new BufferedReader(new FileReader("src/data/" + in + ".txt"));
int temp = Integer.parseInt(br.readLine());
if (temp == 0)
this = new Door (); //this is apparently not allowed
/*continue to instantiate the Door's fields from the data file*/
}
和门类:
public class Door extends MapObject {
public Door () {}
}
我意识到这可能不是解决此问题的最佳方法,但它引起了人们的好奇心,即这不起作用。有没有办法做到这一点?超级的构造函数是否选择了它的子类?