Anubian Noob
Anubian Noob

Reputation: 13596

Inheritance causing errors with constructors?

I have a class called CreatureAi with the following code.

public class CreatureAi {
    public Creature creature;

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

I have a class called PlayerAi which extends it.

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.

However, Netbeans gives me this error.

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.

Why am I getting this error?

Upvotes: 0

Views: 67

Answers (1)

nachokk
nachokk

Reputation: 14413

When you write your subclass, implicit calls super() that is in super type constructor.

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

As you show in your code , your base class doesn't have no-arg constructor. So your child is not valid. You have to call one valid super constructor.

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

Alternative if you can modify your CreatureAi, you can add default no-args constructor.

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.

Upvotes: 3

Related Questions