Help with interfaces

I am a beginning coder trying to understand the best way to organize my code using inheritance, composition, and interfaces in a program that models a simple ecosystem. I apologize in advance for not knowing how word my question.

My code use the following classes:

  • Animal
  • Sheep extends Animal
  • Bear extends Animal
  • Wolf extends Animal implements IPackAnimal. It contains extra methods that keep track of which animals are in its pack.

The main method iterates through an arraylist of Animal Objects:

for (Animal a : animals) {
     a.execute();
}

The above structure works well. Animal class attempts to implement a strategy pattern as follows:

for (IBehavior b : behaviors) {
    b.execute();
}

Behavior classes are Graze, Hunt, Mate, Wander and what you’d expect them to do. Sheep is given graze, mate, wander. Bear is given hunt, mate, wander. This part also worked just fine.

However, I have run into a problem when I tried to implement the Wolf class as a IPackAnimal using a new strategy PackMate. PackMate is intended to extend Mate and override the “doMate” function so that when two IPackAnimals mate the form a pack.

The problem is that the Mate class expects an Animal not an IPackAnimal. If I pass an Animal to the Mate class from the PackMate class, it does not have access to the methods of the IPackAnimal. If I pass it an IPackAnimal, it throws an error because it expects an Animal object.

I do not the Animal object to implement IPackAnimal because not all animals are pack animals i.e. Bears. My first attempt at solving the problem involved casting because all IPackAnimals are animals by definition but this was too complicated, seems like bad form, and I couldn’t get it to work anyway.

Next I thought I could code a “getSelf()” which would return the correct object type depending on what was needed:

  IPackAnimal getSelf() {
    return (IPackAnimal) this;
  }
  Animal getSelf() {
    return (Animal) this;
  }

  IPackAnimal getSelf() {
    return (IPackAnimal) this;
  }
  Animal getSelf() {
    return (Animal) this;
  }

  IPackAnimal getSelf() {
    return (IPackAnimal) this;
  }
  Animal getSelf() {
    return (Animal) this;
  }

The error is "the return type is incompatible with Particle_Base.Animal.getSelf(). The code is located on github at https://github.com/cravens1968/Particle_Base.git. Any insights into the correct strategy for handling this situation would be greatly appreciated.

1 Like

Can you please edit your post to make sure your code is formatted?

To format your code, highlight it and press the code button (it looks like </> ) in the editor. This will surround your code with three tickmarks:

```
// code goes here
```

These three tick marks will preserve your code’s indentation and add syntax highlighting, which makes your code much easier to read.

1 Like