2015-12-03 121 views
1

我刚刚发布了关于抽象方法,我认为这是它不能编译的原因。方法不是抽象的,也不会覆盖方法

超类

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

error:Goblin is not abstract and does not override abstract method getxP() in Monster

所以我不知道这是怎么回事这里的代码是在方面构造超类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; 
    } 
} 
+1

你需要重写'getxP();'in 'Goblin'如果你扩展一个'abstract'类,你必须'覆盖'所有'ABSTRACT'方法。 – 3kings

+2

我认为这个错误是不言自明的,哪部分编译错误消息不理解? “错误:Goblin不是抽象的,并且不会在Monster中覆盖抽象方法getxP()” – alfasin

回答

2

所以GameCharacterabstract class,有abstract方法。

Monsterabstract class并且具有abstract方法。

而地精是一个具体的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的回答表明,你应该在各自的类别来实现这些。

+0

谢谢。我试过了,但仍然有相同的错误。我以@Dromlius的身份说过,并且说它不是抽象的。它似乎现在工作 – Klate

1

制作抽象方法意味着你要在一个子类中实现它。在你的情况下,你将你的get方法声明为抽象的,这在你的场景中毫无意义。

而是写的:

public abstract int getXX(); 

写:

public int getXX() { 
    return XX; 
} 

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

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

+0

谢谢你真的帮助。谢谢你的解释。 – Klate

相关问题