Search code examples
javaclassinterfaceinstances

Save different class instances in a list


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.


Solution

  • 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.