Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 328
Wouter Avatar asked Oct 15 '25 17:10

Wouter


2 Answers

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.

like image 170
Ted Hopp Avatar answered Oct 18 '25 11:10

Ted Hopp


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

like image 30
Choraimy Avatar answered Oct 18 '25 11:10

Choraimy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!