Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of "? extends A"? [duplicate]

Tags:

java

generics

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>();
like image 271
J_Strauton Avatar asked Jan 31 '26 03:01

J_Strauton


1 Answers

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

like image 106
Afzaal Ahmad Zeeshan Avatar answered Feb 01 '26 16:02

Afzaal Ahmad Zeeshan