Search code examples
javacomparable

Interface implementing comparable?


We are a couple of friends designing a game for fun. In our game we have all enemies implement a Combatable interface letting implementors decide how they would like to do combat, this has made the addition of different kinds of enemies very easy. We have (we are at the testing stage) a turret that shoots at the closest enemy every second if that enemy is within range.

We would like to somehow let this interface implement Comparable<Combatable> so that we can sort our collection by distance from tower so we only need to check if the first element in the collection is within attackrange. We realized a simple solution would be to create a wrapper class for the combatable that does nothing else besides implement Comparable but do we really have to do this? I realize it makes little sense to think of an interface implementing another interface but sense aside it is very convenient for this specific use.


Solution

  • An interface can't implement another interface, but it can extend any amount of other interfaces.

    Just do

    interface Combatable extends Comparable<Combatable> {