Python中文网

一个关于 编程问题的解答网站.

有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Warrior不是抽象的,也不会重写Hero中的抽象方法getName()

public interface BattleReady{
    abstract int getHealth();
    abstract String getName();
}
public abstract class Hero implements BattleReady{
  private int health;
  private int level;
  private int experience;
  private int maxHealth;
  private double nextLevelExperience;
  private Inventory inventory;

  public Hero() {
    health = 100;
    maxHealth = 100;
    level = 1;
    nextLevelExperience = 100;
    inventory = new Inventory();  
  }

  public Hero(int health, int level, int experience, int maxHealth,int nextLevelExperience, Inventory inventory){
    this.health = health;
    this.level = level;
    this.experience = experience;
    this.maxHealth = maxHealth;
    this.inventory = inventory;
    this.nextLevelExperience = nextLevelExperience;
  }

  public boolean takeDamage(int amount)
    {
      health = health - amount;
      if(health <= 0)
      {
        health = 0;
        return false;
      }
      return true;
    }

  public int getLevel() { return level; }
  public int getHealth() { return health; }
  public void setHealth(int health) { this.health = health; }
  public int getExperience() { return experience; }
  public double getNextLevelExperience() { return nextLevelExperience; }

  public void setExperience(int experience) { this.experience = experience; }
  public int getMaxHealth() { return maxHealth; }
  public void setMaxHealth(int maxHealth) { this.maxHealth = maxHealth; }
  public Inventory getInventory() { return inventory; }

  public abstract void display();
  public abstract void upgradeStats();         

  public void incrementLevel() 
  {
    double nextLevel = this.getNextLevelExperience();
    nextLevel += getNextLevelExperience();
    level += 1;
    upgradeStats();
    System.out.println("Hero has leveled up!");
  }   

  public int attack(){
    return (int)(Math.random()*level);
  }

  public abstract String getName();
}
public class Warrior extends Hero {
  public Warrior() {
    super();
  }
  public  Warrior(int health, int level, int experience, int maxHealth) {

  }

  public void upgradeStats() {
    int h = this.getHealth();
    h += this.getLevel()*12;
  }

  public String toString() {
    return "Warrior";
  }
}

我需要帮忙解决这个错误

我在编译时遇到了这个错误

Warrior.java:1: error: Warrior is not abstract and does not override abstract method getName() in Hero public class Warrior extends Hero

Requirement:getName()-如果“战士是英雄”(这应该是一个抽象方法还是不在英雄类中?)则需要返回


共 (1) 个答案

  1. # 1 楼答案

    因为getName()方法是抽象的,所以您必须在Warrior类中重写它,如下所示:

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

    不要忘记对display()-方法做同样的事情

    为了清晰起见,我建议用@Override注释覆盖的方法。像IntelliJ这样的IDE可以自动为您做到这一点