1

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Class<T> is a class, not an instance. ControlBase itself (as in, the idea of a control base) is an instance of Class<ControlBase>. In your first example, you're looking for void registerController(T c). You probably won't see Class<T> until you get into some more advanced Java, as it's only used for reflection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.