Skip to Content
Java Generics and Collections
book

Java Generics and Collections

by Maurice Naftalin, Philip Wadler
October 2006
Intermediate to advanced
284 pages
8h 30m
English
O'Reilly Media, Inc.
Content preview from Java Generics and Collections

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Understanding Java 8 Generics

Understanding Java 8 Generics

Ken Kousen
Java Generics and Collections, 2nd Edition

Java Generics and Collections, 2nd Edition

Maurice Naftalin, Philip Wadler
Java 8 Lambdas

Java 8 Lambdas

Richard Warburton

Publisher Resources

ISBN: 0596527756Supplemental ContentErrata Page