簡體   English   中英

從子類到超類獲取字段

[英]getting fields from subclass to superclass

我正在制作塔防游戲,但遇到了一些問題。 我創建了一個抽象類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;

這是“敵人”類中的功能之一。

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();
    }
}

當前,我的問題是,即使我所有的敵人都是BasicEnemy,並且應該擁有3的生命值,isDead()函數始終會返回true(因為它們至今尚無法承受傷害)。

我假設isDead()函數使用Enemy類中的health字段(尚未設置任何內容),而不是使用子類中的health字段。

我不想使用抽象函數,因為如果我要制造幾種類型的敵人,那將導致很多重復的代碼。 我基本上希望我的超類中的函數使用子類中的字段,或者將超類中的字段設置為子類中的值。

您已經在Enemy定義了字段health ,為什么還要在BasicEnemy定義它? Enemy任何子類中刪除health字段,它將起作用。

問題是因為您在子類和超類中都聲明了字段,所以子類以這些字段的2個副本結尾,例如Enemy.currentXBasicEnemy.currentX 在敵人的方法是檢查中聲明的領域Enemy ,但BasicEnemy子類修改它自己的領域。 刪除BasicEnemy重復的聲明,它應該可以正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM