3

If I have a list like this:

static ArrayList<? extends A> list = new ArrayList<A>();

What is the point of ? extends A? Does it mean that I am making a list of only subclasses that MUST inherit from A?

Normally I do it like this:

static ArrayList<A> list = new ArrayList<A>();
user2864740
  • 60,010
  • 15
  • 145
  • 220
J_Strauton
  • 2,270
  • 3
  • 28
  • 70

2 Answers2

3

extends keyword means that the class on the left of this keyword would be using all the methods and properties from the class that is one the right side. ? wouldn't be there. Some name would be. A name of a class.

static ArrayList<? extends A> list = new ArrayList<A>();

In the above code, you're making a new ArrayList object which uses (implements/extends) the Class A for its methods and properties but is not in real A.

static ArrayList<A> list = new ArrayList<A>();

Whereas in the second code that you usually use, you're actually creating an Object which uses class A in real.

In Java we call it inheritance where one class inherits all the properties and functions of the other class.

http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

Afzaal Ahmad Zeeshan
  • 15,669
  • 12
  • 55
  • 103
2

From Java Docs:

The upper bounded wildcard, <? extends Foo>, where Foo is any type, matches Foo and any subtype of Foo.

So, answering the question "Does it mean that I am making a list of only subclasses that MUST inherit from A?"

It means that you are making a list of objects which types are A or inherit from A.

Edit:

One difference is that in the second code

ArrayList<A> list = new ArrayList<A>();

you will be able to refer to the type A anywhere in the code.

Christian Tapia
  • 33,620
  • 7
  • 56
  • 73