继承导致构造函数错误?

时间:2013-12-06 01:08:36

标签: java inheritance constructor

我有一个叫做CreatureAi的类,代码如下。

public class CreatureAi {
    public Creature creature;

    public CreatureAi(Creature creature) {
        this.creature = creature;
        this.creature.setCreatureAi(this);
    }
    // There's more, I'm shortening it.

我有一个名为PlayerAi的类,它扩展了它。

public class PlayerAi extends CreatureAi {
    private FieldOfView fov;
    private Player player;

    public PlayerAi(Player player, FieldOfView fov) {
        this.player = player;
        this.player.setCreatureAi(this);
        this.fov = fov;
    }
    // These are the only constructors.

然而,Netbeans给了我这个错误。

constructer CreatureAi in class CreatureAi cannot be applied to the given types.
required: Creature
found: No arguements
reason: Actual and formal lists differ in length.

为什么我收到此错误?

1 个答案:

答案 0 :(得分:3)

当你编写子类时,隐式调用super()是超类型构造函数。

public PlayerAi(Player player, FieldOfView fov) {
        super(); // this call "father" constructor
        this.player = player;
        this.player.setCreatureAi(this);
        this.fov = fov;
}

当您在代码中显示时,您的基类没有no-arg构造函数。所以你的孩子无效。你必须调用一个有效的超级构造函数。

public PlayerAi(Player player, FieldOfView fov) {
            super(//??creature); // you have to pass something here
            this.player = player;
            this.player.setCreatureAi(this);
            this.fov = fov;
    }

如果您可以修改CreatureAi,则可以添加默认的no-args构造函数。

public class CreatureAi {
    private Creature creature;

    public CreatureAi(){}

    public CreatureAi(Creature creature) {
        this.creature = creature;
        this.creature.setCreatureAi(this);
    }
    // There's more, I'm shortening it.