Java Noob Java Noob - 1 year ago 66
Java Question

Use interfaces to implement pre-coded abilities

I'm making a game with different types of mobs in it. There is also a list of interfaces, each representing an ability that a mob can have. Let's say I have 100 objects extending the mob class, each one containing a different list of mob-applicable abilities (swing, explode, jump, etc.). All implementing these interfaces would do is to add blank methods to the class. If the usage of the ability is constant between all mobs, how would I make it so the ability is
pre-written so that I wouldn't need to write it again for every mob that implements it?

I do know of default methods, but they are static and don't have access to any of the mob's variables unless I pass "this" as a parameter which is something I don't want to do.

I am also aware that were there to be a solution to the problem using interfaces, those interfaces could only ever be implemented by a mob.


Answer Source

If I understand it correctly, a possible solution is to compose abilities instead of inheriting them.

interface Ability {
    void doAbility();

class Firebending implements Ability {
    private Mob mob;

    public Firebending(Mob mob) {
        this.mob = mob;

    void doAbility() {
        // mutate mob's state to spit fire, and attack the world
} // repeat this for each ability you have, flying, x-ray vision, doing taxes etc

class Mob {
    private Ability[] abilities;

    public Mob(Ability[] abilities) {
        this.abilities = abilities;

With something like this, you can build different mobs on the fly each with a different set of abilities, suitable for when the mob varieties outnumber the number of abilities. And yes, this would involve designing your Mob class(es) to be flexible to be mutated this way.