【问题标题】:Method is not abstract and does not override method [duplicate]方法不是抽象的,也不会覆盖方法[重复]
【发布时间】:2015-12-03 04:28:42
【问题描述】:

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

超级类

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 不是抽象的,也没有覆盖抽象方法 怪物中的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;
    }
}

【问题讨论】:

  • 你需要在Goblin 中覆盖getxP(); 如果你扩展一个abstract 类,你必须OVERRIDE 它的所有ABSTRACT 方法。
  • 我认为错误是不言自明的,编译错误消息的哪一部分你不明白? “错误:Goblin 不是抽象的,不会覆盖 Monster 中的抽象方法 getxP()”

标签: java


【解决方案1】:

所以GameCharacter 是一个abstract class 并且有abstract 方法。

Monsterabstract class 并具有abstract 方法。

而 Goblin 是一个具体的 class,应该实现任何未被超类实现的 abstract 方法。我怀疑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 的回答所暗示的那样,您可能应该在它们各自的类中实现这些。

【讨论】:

  • 谢谢。我试过这个,但它仍然有同样的错误。我按照@Dromlius 所说的做了,并使它变得非抽象。现在好像可以了
【解决方案2】:

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

而不是写:

public abstract int getXX();

写:

public int getXX() {
   return XX;
} 

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

如果你想让你的方法保持抽象,你必须在你的非抽象子类(Goblin)中实现所有抽象超类(GameChar & Monster)的所有抽象方法

【讨论】:

  • 感谢您的帮助。也谢谢你的解释。
猜你喜欢
  • 2021-09-01
  • 2014-06-20
  • 2014-01-16
  • 1970-01-01
  • 1970-01-01
  • 2014-04-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多