Home > Mobile >  ArrayList of Objects That Inherit from Parent Classes in Java
ArrayList of Objects That Inherit from Parent Classes in Java

Time:07-01

I have a class, controlBase, that is inherited by other child classes. How can I make a list of any of these child classes?

I have tried:

private ArrayList<? extends controlBase> controllers = new ArrayList();

However, this doesn't allow any classes to be added to it. With the above example, this throws an error:

public <T extends controlBase> void registerController(Class<T> c) {
    controllers.add(c);
}

An error is also thrown when I execute:

controllers.add(new controlBase());

or

controllers.add(new joystick()); // Joystick is a child-class of controlBase

This does not allow any classes to be added, even in the first example where it explicitly states that the class extends controlBase.

How can I make this arrayList be only of objects that extend the controlBase class?

CodePudding user response:

You're misunderstanding the point of the call-site variance annotations. ? extends ControlBase is meant to imply that data can be safely read from the container as ControlBase but that nothing can be written to it. See my answer on a similar question for more details about when you would want to use this syntax, or PECS for a summary of the general rules.

In your case, you want, quite simply, ArrayList<ControlBase>. Every Joystick is a ControlBase, by the rules of inheritance, so you can add any subclass to that ArrayList whenever you like.

  • Related