简体   繁体   中英

Java OOP instance of class

I have following classes structure extention: Entity > Creature > (abstract) Player > Mage . In Mage class I implement interface iCastable with method castSpell() . In main method I create new Mage(...) .

Problem is that when I send it as a prop of Player class someMethod(Player player) , I cannot use methods implemented from interface iCastable . I can only use methods from Creature class via player.getCreaure.whaterver() because Player extend it. How can I solve that issue?

I do not want to send it as a prop of Mage class, because I want to use all my other classes like Warrior for example. I also want to avoid player instanceof Mage , because if I had 1000 classes I must do 1000 check for every method. Do you have any ideas how to solve that?

EDIT added code

public class Creature extends Entity {...}

public abstract class Player extends Creature {
    public Player(String name) {
        super(name);
    }
    public abstract void attack();
}
public class Mage extends Player implements iCastable {
    ...
    @Override
    public void castSpecial() {...}
}

public static void main(String[] args) {
   Mage mage = new Mage("Mage");
   Duel duel = new Duel(mage, monsters);
}
public class Duel {
    private Player player;
    ...
    public Duel(Player player, ArrayList<Monster> monsters) {
        this.player = player;
        ...
    }
    private void castSpecial() {
        // error here
        player.castSpecial();
    }
}

I am trying to do something like player.getInstanceClass(mage, warrior or whatever).cashSpecial()

Your method can be written like this:

private void castSpecial() {
    if (player instanceof iCastable) {
        ((iCastable) player).castSpecial();
    }
}

The instanceof performs a runtime check to see if the Player instance has the correct subclass. If the check succeeds then the type cast will also succeed. (If you do the type cast without a "guard", then it will throw an ClassCastException if the player doesn't have the required type.)

Obviously, if the player does not have spell casting ability, the method does nothing.


Note: the interface name iCastable is wrong from two perspectives.

  1. A class or interface name should never start with a lowercase letter.

  2. The name is wrong. ICastable implies that you would "cast" a Mage . In fact, the Mage is the subject, that casts the spell, not the spell that is cast. A better name might be ISpellCaster .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM