Identifying Subclasses

I am making a simple 2D platform game and I have run into a slight problem with the Spells I want the player and NPCs to use.
I have an abstract class Spell and a set of subclasses extending Spell. These subclasses indicate the element of the spell, so one subclass might be Fire_Spell. I want to be able to receive a Spell and do something like


if(spell.getClass() == Fire_Spell){
     doStuff();
}

But I can’t figure out how to identify if spell is a certain subclass since whenever I try to compare the instance of Spell I have (which will never really be a Spell, always one of the subclasses of Spell) I just can’t find a way that doesn’t either end in an error or which gives a faulty answer.

I have tried something like “attack.isAssignableFrom(Fire_Spell)” and “attack.getClass().isAssignableFrom(Fire_Spell)” but those just say that “Fire_Spellcannot be resolved to a variable” so I wonder what I’m doing wrong.

spell instanceof FireSpell

But it would be better to structure your code to avoid the need to use instanceof, it tends to be ugly code, and you will have long tails of if…else…else… for all your subclasses. Rather have a method like AbstractSpell.cast() that each spell implements, then you can ask a spell to act (or display or whatever) without needing to know which subclass you have.

if(spell.getClass() == Fire_Spell.class){
doStuff();
}

or

spell.getClass().isAssignableFrom( Fire_Spell.class )

or

spell instanceof Fire_Spell

Do this:


abstract class Spell {
    public abstract void doStuff();
}
class Fire_Spell extends Spell {
    @Override
    public void doStuff() {
        // do stuff
    }
}
...
spell.doStuff();

@superminer362 please remove your fist example, it is the worst possible “solution” I can think of

What’s the real problem? If you’re examining the type of something…that usually has a high stink value. Normally you do:

[icode]spell.doSomething();[/icode]

I don’t think polymorphism is always the best way. In some cases, some subclasses will have unique fields or methods. And in some others, one may just want to cope with some certain subclasses and ignores the others.

Inspecting a type is brittle, error prone and exponentially more work. If polymorphism isn’t the solution (and I’m not saying that it always is)…what’s the problem?

EDIT: And before anyone misunderstands my statement: If I were designing a spell system all spells would be the same class…there’d be no polymorphism.