Chapter 2. Subtyping and Wildcards

Now that we’ve covered the basics, we can start to cover more-advanced features of generics, such as subtyping and wildcards. In this section, we’ll review how subtyping works and we’ll see how wildcards let you use subtyping in connection with generics. We’ll illustrate our points with examples from the Collections Framework.

Subtyping and the Substitution Principle

Subtyping is a key feature of object-oriented languages such as Java. In Java, one type is a subtype of another if they are related by an extends or implements clause. Here are some examples:

Integer

is a subtype of

Number

Double

is a subtype of

Number

ArrayList<E>

is a subtype of

List<E>

List<E>

is a subtype of

Collection<E>

Collection<E>

is a subtype of

Iterable<E>

Subtyping is transitive, meaning that if one type is a subtype of a second, and the second is a subtype of a third, then the first is a subtype of the third. So, from the last two lines in the preceding list, it follows that List<E> is a subtype of Iterable<E>. If one type is a subtype of another, we also say that the second is a supertype of the first. Every reference type is a subtype of Object, and Object is a supertype of every reference type. We also say, trivially, that every type is a subtype of itself.

The Substitution Principle tells us that wherever a value of one type is expected, one may provide a value of any subtype of that type:

Substitution Principle: a variable of a given type may be assigned a value of any subtype of that ...

Get Java Generics and Collections now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.