سؤال

I have a general Java question.

I've got different 'spell' classes, they aren't made of 1 object because they differ too much. So I created for example 3 classes:

  1. called Ice ice = new Ice();
  2. called Hurricane hurricane = new Hurricane();
  3. called Bomb bomb = new Bomb();

Those spells do have same corresponding methods (getCooldown(), getName(), cast()).

So I want these class instances to be saved in a certain list/hashmap where I can iterate through. When iterating through the instances I'll check if getName() equals a certain name, and if that's the case return the certain class instance.

I hope this is possible, if not I hope someone can help me thinking of another idea.

هل كانت مفيدة؟

المحلول

You can have all three classes implement a common interface and declare the list to contain instances of the interface.

interface Spell {
    int getCooldown();
    String getName();
    void cast();
}

public class Ice implements Spell {
    @Override
    public int getCooldown() { . . . }
    @Override
    public String getName() { . . . }
    @Override
    public void cast() { . . . }
    // more stuff specific to Ice
}
public class Hurricane implements Spell {
    // similar to above
}

Then you can do something like:

List<Spell> spells = new ArrayList<>();

spells.add(new Hurricane());
spells.add(new Ice());

You can also do this with a common base class, but coding to an interface generally provides more flexibility.

نصائح أخرى

Try implementing an interface or base class that they all derive from, then make a List containing that interface or base class.

Create a basic abstract class or an interface for all your spells, for exmaple:

public abstract class Spell {

    public abstract int getCooldown();

    public abstract String getName();

    public abstract void cast();
}

Now let your spells extend the Spell class. Then create your List like this:

List<Spell> spells = new ArrayList<>();

Now you can add any Spell to spells list.

Define an interface that has methods getCooldown(), getName(), cast(). Then make all classes implement that interface. Now create a list as follows and add to it :

List<MyInterface> list = new ArrayList<MyInterface>();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top