Java 从子类到超类获取字段
我正在做一个塔防游戏,我有一些问题。我创建了一个抽象类,除了使用这些字段的两个方法之外,还包含这些字段Java 从子类到超类获取字段,java,inheritance,field,abstract,Java,Inheritance,Field,Abstract,我正在做一个塔防游戏,我有一些问题。我创建了一个抽象类,除了使用这些字段的两个方法之外,还包含这些字段 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 i
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-List-enemyList;
public void addEnemy(字符串类型){
开关(类型){
//这可能不是使用字符串的最佳解决方案,但不管怎样
案例“基本”:
enemyList.add(新的BasicEnemy(startingX,startingY,this));
打破
}
}
我的问题出现了,当我试图循环我的敌人列表,看看是否有敌人死亡
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();
}
}
private void checkfordeadfeeds(){
List=new ArrayList();
for(敌人:enemyList){
if(敌方.isDead()){
死亡敌人。添加(敌人);
}
}
for(敌人:死敌){
消灭敌人;
register.increaseBalance(敌方.getBounty());
notifyAllListeners();
}
}
目前我的问题是isDead()函数总是返回true,即使我的所有敌人都是BasicEnemy并且应该有3点生命值(因为他们目前还没有办法承受伤害)
我假设isDead()函数使用敌方类的health字段,而不是子类的health字段,该字段尚未设置为任何值
我不想使用抽象函数,因为如果我要创建几种类型的敌人,这将导致大量重复代码。
我基本上希望我的超类中的函数使用子类中的字段,或者将超类中的字段设置为子类中的值。您已经在
敌人中定义了字段健康,为什么还要在基本健康中定义它?从敌方
的任何子类中删除健康
字段,它就会工作。你已经在敌方
中定义了健康
字段,为什么还要在基本健康
中定义它?从敌方
的任何子类中删除健康
字段,它就会起作用。问题在于,您同时在子类和超类中声明了字段,因此子类最终会得到这些字段的两个副本,例如敌方.currentX
和基本类.currentX
。敌方中的方法正在检查敌方
中声明的字段,但是基本类
子类正在修改它自己的字段。删除BasicEnemy
中的重复声明,它应该可以正常工作。问题在于,您同时在子类和超类中声明字段,因此子类最终会得到这些字段的两个副本,例如敌方.currentX
和BasicEnemy.currentX
。敌方中的方法正在检查敌方
中声明的字段,但是基本类
子类正在修改它自己的字段。删除BasicEnemy
中的重复声明,它应该可以正常工作