【问题标题】:getting fields from subclass to superclass从子类到超类获取字段
【发布时间】:2014-07-15 15:29:47
【问题描述】:

我正在制作一款塔防游戏,但遇到了一些问题。我创建了一个抽象类 Enemy,除了一些使用这些字段的方法之外,它还具有这些字段。

public abstract class Enemy
{
    public int currentX, currentY;
    //currentX(and Y)PF are used for the pathfinder, they are currentX(and Y) - 1
    public int currentXPF, currentYPF;
    public int health;
    public int velocity;
    public int defense;
    public String orientation;

这是 Enemy 类中的函数之一。

public boolean isDead(){
    if(health == 0){
        return true;
    }
    return false;
}

我想做的是在一个子类中定义这些字段(这样我就可以为每种类型的敌人拥有一个子类,而它们没有相同的值),但我在实际使其工作时遇到了问题。

public class BasicEnemy extends Enemy
{
    public int currentX, currentY;
    public int velocity;
    public int health;
    public int defense;
    public String orientation;

    private static int bounty = 50;


    public BasicEnemy(int currentX,int currentY, Board board) {

        this.health = 3;
        this.defense = 0;
        this.velocity = 1;

        this.currentX = currentX;
        this.currentY = currentY;


        this.currentXPF = currentX - 1;
        this.currentXPF = currentY - 1;

        this.orientation = "right";

        //moveSelf is defined in superclass
        this.moveSelf(board);
    }

在另一个类中,我有一个敌人列表和一个将敌人添加到列表中的函数

private List<Enemy> enemyList;

public void addEnemy(String type){
switch(type){
//probably not the best solution to use strings for this but whatever
    case "basic":
    enemyList.add(new BasicEnemy(startingX,startingY, this));
    break;
}
}

当我尝试循环遍历我的敌人列表以查看是否有敌人死亡时,我的问题出现了

private void checkForDeadEnemies(){
    List<Enemy> deadEnemies = new ArrayList<>();
    for (Enemy enemy : enemyList){
        if(enemy.isDead()){
            deadEnemies.add(enemy);
        }
    }
    for(Enemy enemy : deadEnemies){
        enemyList.remove(enemy);
        register.increaseBalance(enemy.getBounty());
        notifyAllListeners();
    }
}

目前我的问题是 isDead() 函数总是返回 true,即使我所有的敌人都是 BasicEnemy 并且应该有 3 生命值(因为他们还没有办法受到伤害)。

我假设 isDead() 函数使用 Enemy 类中的 health 字段,它尚未设置为任何值,而不是使用子类中的 health 字段。

我不想使用抽象函数,因为如果我要制造多种类型的敌人,那会导致大量重复代码。 我基本上希望我的超类中的函数使用子类中的字段,或者将超类中的字段设置为子类中的值。

【问题讨论】:

    标签: java inheritance field abstract


    【解决方案1】:

    您已经在Enemy 中定义了字段health,为什么还要在BasicEnemy 中定义它?从Enemy 的任何子类中删除health 字段,它将起作用。

    【讨论】:

      【解决方案2】:

      问题是因为您在子类和超类中都声明了字段,所以子类最终会得到这些字段的 2 个副本,例如 Enemy.currentXBasicEnemy.currentX。 Enemy 中的方法正在检查Enemy 中声明的字段,但BasicEnemy 子类正在修改它自己的字段。删除BasicEnemy 中的重复声明,它应该可以正常工作。

      【讨论】:

        猜你喜欢
        • 2017-05-08
        • 1970-01-01
        • 2023-03-19
        • 1970-01-01
        • 1970-01-01
        • 2019-09-16
        • 1970-01-01
        • 2011-03-25
        • 2013-07-20
        相关资源
        最近更新 更多