提问者:小点点

方法不抽象,不会覆盖方法[重复]


我刚刚发布了关于抽象方法的文章,我认为这是它无法编译的原因。

超级类

public abstract class Monster extends GameCharacter {

   public abstract int getxP();      
   protected int monsterXP;

     public Monster(String name, int health, int attack, int xp) {
         super(name, health, attack);
         this.monsterXP = xp;
     } 

我的子类

public class Goblin extends Monster {

    public Goblin(String name, int health, int attack, int xp){
        super(name, health, attack, xp);
    }

    public Goblin(){
        this("Goblin", 70, 15, 2);
    }
} 

错误:Goblin不是抽象的,不会覆盖Monster中的抽象方法getxP()

所以我不确定这里发生了什么,超级类GameCharacter的代码在构造函数方面是相同的。我不明白为什么xp与名称、健康和攻击不同。

为了弄清楚我是如何安排我的超级班级的

public abstract class GameCharacter {

    public abstract String getName();
    public abstract int getHealth();
    public abstract int getAttackPower();

    protected String gameCharacterName;
    protected int gameCharacterHealth;
    protected int gameCharacterAttack;

    public GameCharacter(String name, int health, int attack){
        this.gameCharacterName = name;
        this.gameCharacterHealth = health;
        this.gameCharacterAttack = attack;
    }
}

共2个答案

匿名用户

所以GameCharacter是一个抽象类并且具有抽象方法。

Monster是一个抽象类并且具有抽象方法。

而Goblin是一个具体的,应该实现任何未被超类实现的抽象方法。我怀疑getxP()恰好是编译器遇到的第一个丢失并在此之后失败的方法。如果你实现了getxP(),其他丢失的方法也应该会导致编译错误,假设它们还没有在一些我们在这里看不到的代码中实现。

要以代码形式回答,Goblin需要如下所示:

public class Goblin extends Monster {

    public Goblin(String name, int health, int attack, int xp){
        super(name, health, attack, xp);
    }

    public Goblin(){
        this("Goblin", 70, 15, 2);
    }

    @Override
    public int getxP() {
        return monsterXP;
    }

    @Override
    public String getName() {
        return gameCharacterName;
    }

    @Override
    public int getHealth() {
        return gameCharacterHealth;
    }

    @Override
    public int getAttackPower() {
        return gameCharacterAttack;
    }
}

然而,正如@Dromlius的回答所暗示的,您可能应该在它们各自的类中实现这些。

匿名用户

使方法抽象意味着您将在子类中实现它。在您的情况下,您将get方法声明为抽象,这在您的场景中没有什么意义。

而不是写:

public abstract int getXX();

写:

public int getXX() {
   return XX;
} 

它不会抱怨你的Monster类中的攻击、健康等,因为你也声明了Monster类的抽象,基本上是说:“我知道这个类中有抽象方法(部分继承自GameCharacter),但我会在下一个非抽象子类中实现它们(在你的例子中是Goblin)。

如果你想保持你的方法抽象,你必须实现所有抽象超类的所有抽象方法(GameChar