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?

uksz
  • 18,239
  • 30
  • 94
  • 161

2 Answers2

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.

Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
1

It this what you are looking for?

List<? extends Product> list
Sergii Bishyr
  • 8,331
  • 6
  • 40
  • 69
  • Exactly! THanks so much! – uksz Apr 26 '16 at 18:39
  • 2
    @uksz `List` 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. – Boris the Spider Apr 26 '16 at 18:39
  • 1
    In fact the `? extends` is most likely harmful in this case. – Kayaman Apr 26 '16 at 18:40
  • It depends on the usecase. It Also could be implemented as generic `` which is much better or just `List` as @BoristheSpider suggested. – Sergii Bishyr Apr 26 '16 at 18:43
  • 2
    @SergheyBishyr both those examples are for a `List` _or a_ `List`, 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`. – Boris the Spider Apr 26 '16 at 18:44
  • @BoristheSpider as I understand from the question, it's not about the list that can contain all of the subclasses. So, ` extends Product>` is ok if you want to be able to receive both `List` and `List`. – Sergii Bishyr Apr 26 '16 at 18:53
  • @BoristheSpider I meant receive as argument in some method. E.g. `doSomething(List extends Product> list)`. In this case you can pass both `List` and `List` to `doSomething` – Sergii Bishyr Apr 26 '16 at 18:58