dimanche 16 mai 2021

Creating an adapter for a java interface with a method which has as parameter the interface itself

Probably the title is a bit confusing but the code will be pretty straight forward.

I have the class Character and the interface ICharacter and I have to make an Adapter so Character can work with ICharacter. The problem is that in the interface I have the method attack(ICharacter) and in class Character I have the method clobber(Character) and I don't know how to make them work.

Please note that I'm not allowed to modify the code in Character or ICharacter, only changes should go in CharacterAdapter class

public interface ICharacter {
    void attack(ICharacter other);
}

public class Character {
    private int health = 100;
    public void decHealth(int hit) {
        health = (health < hit)?0: health - hit;
        System.out.println("health = " + health);
    }
    public void clobber(Character c) {
        c.decHealth(5);
    }
}

And here is the CharacterAdapter:

public class CharacterAdapter implements ICharacter {

    Character actor;

    public CharacterAdapter(Character character) {
        actor = new Character();
    }

    @Override
    public void attack(ICharacter other) {
        actor.clobber(???)
    }

}

Aucun commentaire:

Enregistrer un commentaire