0

I am wondering how I can create an array list of classes that extend certain abstract class. Lets say I have abstract class:

abstract class Product{
}

and some class that extends it:

public class Toy extends Product{
}

public class TV extends Product{
}

I would like to implement a list of classes that extend abstract class Product. How can I do that?

3
  • Can you clarify an array list of classes? Commented Apr 26, 2016 at 18:37
  • I would like to have an array that will store multiple products. Commented Apr 26, 2016 at 18:38
  • Unless you have some specific methods you are trying to override, then TV and Toy are more like instances of a Product, than needing to be classes. Commented Apr 26, 2016 at 18:40

2 Answers 2

5

You need:

final List<Product> list = new ArrayList<>();

This means that you have a List of types that extends or implements Product.

You should not use:

List<? extends Product> list = new ArrayList<>();

Because list.add will be a compilation error.

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

Comments

1

It this what you are looking for?

List<? extends Product> list

7 Comments

Exactly! THanks so much!
@uksz List<Product> will also work in every case - the ? extends is not necessary in this case. This is only necessary in a method receiving a List of a specific type.
In fact the ? extends is most likely harmful in this case.
It depends on the usecase. It Also could be implemented as generic <T extends Product> which is much better or just List<Product> as @BoristheSpider suggested.
@SergheyBishyr both those examples are for a List<Toy> or a List<TV>, and you not knowing which you have. In this case, it is certainly the wrong approach, as the OP wants a List than can contain both Toy and TV.
|

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.