Java继承编译

标签 java eclipse inheritance compilation

我无法编译具有一个类继承的简单 Java 项目。

如果没有固有的类,项目可以很好地编译,当我添加该类时,我在 Eclipse 中收到消息:“所需项目中存在错误”。奇怪的是,如果我单击“继续”,项目运行正常,但编译后却出现错误消息。我应该怎么做才能避免出现此错误?

这是代码,我有一个主类,但现在我没有在其中执行任何操作。

    public class Person
{
    private String name;
    private int health;
    private int x;
    private int y;
    Random randomGenerator = new Random();  
    public Person(String name,int x,int y)
    {
        this.nom = name;
        this.x = x;
        this.y = y;
        health = randomGenerator.nextInt(100);
    }
    public void Attack(int damage)
    {
        healh+=damage;
    }
    public int getHealth()
    {
        return health; 
    }
}
//Without the class Warrior, I do not get error message
public class Warrior extends Person
{
    protected int damage;
    public void faireAttaque(Person p)
    {
        p.Attack(damage);
    }
}
//When I added the Warrior class, I got the error message

最佳答案

您的子类应该实现构造函数并调用super

public class Warrior extends Person {
    public Warrior(String name, int x, int y)
    {
        super(name,x,y);
    }
    //other stuff
}

关于Java继承编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29549996/

相关文章:

java - 如何找到在eclipse中添加的特定代码行的时间?

c# - Reflection.Emit 创建通用继承方法

java - 是否可以替换 Java 中的公共(public)静态方法?

java - 是否有用于 Java 的免费指纹读取器 API/SDK?

java - 获取 java.lang.IllegalStateException : Neither BindingResult nor plain target object for bean name 'command' available as request attribute

java - 引导层初始化出错

java - 带条件的 XML 到 JSON 转换

java - 为什么我不能在 web.xml 中编辑 servlet 名称?

c++ - C++中的属性继承如何工作?

c++ - 如何创建一个不能被其他类继承的类?