Java继承编译

Java inheritance compilation

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

没有继承 class 项目编译得很好,当我添加 class 时,我在 Eclipse 中收到消息:"Errors exist in required project"。奇怪的是,如果我点击"Proceed",项目运行正常,但编译后出现错误消息。我应该怎么做才不会出现这个错误?

这是代码,我有一个主要的 class 但现在我没有在其中做任何事情。

    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

您的 child class 应该实现构造函数并调用 super

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

首先,您缺少 Warrior class 中的构造函数。你需要它是因为你继承了 Person class 的非默认构造函数。其次,您需要将这些 class 分成两个文件。