SpiroMarshes SpiroMarshes - 1 month ago 11
Java Question

Java inheritance, Looping through each subclass

I'm trying to loop through multiple objects of different types that are all extending the same parent class. For example:

ArrayList<Enchant> enchants = new ArrayList<>();


Inside of the enchants array would be objects of classes that extend an
Enchant
class.

For example:

public class JumpBoost extends Enchant{
public static Item generateItem(){
return something;
}
}


Each object in the enchants ArrayList would have a method called generateItem().

I would like to loop through it using:

for(Enchant enchant : enchants){
enchant.generateItem()
}


I've already tried doing this, but with no luck due to the Enchant class not having the
generateItem()
method.

I essentially just need a way to group and loop through multiple objects of different types.

Answer

You can use polymorphism to solve that problem.
First define the base class/abstract class/interface with the method generateItem(), derive specified classes and override/implement generateItem() method.
Here is implementation with interface:

interface Base{
    void generateItem();
}
class Derived1 implements Base{
    @Override
    public void generateItem() {
        System.out.println("generateItem() from Derived1");
    }
}
class Derived2 implements Base{
    @Override
    public void generateItem() {
        System.out.println("generateItem() from Derived2");
    }
}
class Main {
    public static void main(String[] args) {
        List<Base> list = new ArrayList<>();
        list.add(new Derived1());
        list.add(new Derived2());
        list.forEach(Base::generateItem);
    }
}

The output is:

generateItem() from Derived1
generateItem() from Derived2

For more, you can read about polymorphism here.

Comments