在我的代码中,我有一个叫做Game
的超类,它的子类Tower
。 Tower
也有它的子类Catapult
。 凯达普子类看起来是这样的:我无法获得我的数组列表中的对象
public class Catapult extends Tower {
public Catapult(){
super(5,3);
}
}
它要求Tower
构造与恒定的整数值5和3。然后,它的超Tower
看起来是这样的:
public class Tower extends Game {
private int damage;
private int timeStep;
private int position;
private boolean willFire;
public Tower(int damage, int timeStep){
super.addTower(damage,timeStep);
}
public Tower(int damage, int timeStep, int position,boolean willFire){
this.damage = damage;
this.timeStep = timeStep;
this.position = position;
this.willFire = willFire;
}
public void getDamage(){
super.printDamage();
}
}
所以,现在,具有价值损伤和时间步长(5,3),Tower
调用它的超级构造函数(游戏):
import java.util.ArrayList;
public class Game {
private ArrayList<Enemy> enemies = new ArrayList<Enemy>();
private ArrayList<Tower> towers = new ArrayList<Tower>();
private int corridorLength;
private int currentPosition = 0;
public Game(){}
public Game(int corridorLength){
this.corridorLength = corridorLength;
}
public void addTower(int damage,int timeStep){
this.towers.add(new Tower(damage,timeStep,this.currentPosition,true));
// Add tower with current position corrdor length
System.out.println("Tower added in addTower!");}
public void printDamage(){
System.out.println(this.towers.get(this.currentPosition)); // How to get the damage item?
}
}
所以对象Tower
与它的值被存储在阵列塔(至少我假设如此)。因此,有一个非空阵列称为至少大小为1的塔,我在这里面临一些问题。 首先:当我调用Tower.getDamage()
方法时,它最终调用Game
类中的方法,该方法仅在索引0处打印对象Tower
。但是,当我尝试以其他方式进行操作时,例如像这样打印Game
类中的对象(从Game
类直接调用,而不是通过其Tower
子类调用):
public void getDamage(){
System.out.println(this.towers.get(this.currentPosition));
}
它抛出一个超出范围的数组例外,我不明白的,因为阵列塔应该存储在索引对象0.
第二:如何获得对象内的实际整数t(塔)在索引0?所以,我不能这样做:如果你要打印的塔的伤害
this.towers.get(0).damage
快速浏览一下你的代码,我发现你似乎大大地误用了继承。塔为什么要扩展游戏?没有意义,因为塔怎么能成为一个更专业的子类型的游戏? –
塔是游戏中的一个对象。当我说对象时,我的意思是像简单的对象(汽车和摩托车都是汽车的对象)。 –
塔也不会被添加到塔上的建筑领域。事实上,每一个新的Tower()都会创建一个新的带有空塔列表的游戏。 –