Chapter 2. Subtyping and Wildcards
Now that we’ve covered the basics, we can start to explore more advanced features of generics, such as subtyping and wildcards. In this chapter, we’ll review how subtyping works and see how wildcards let us use subtyping in connection with generics. The Java Collections Framework will serve as the source of our examples; see Part II for details on specific features of the Collections API.
Note
The code examples for this chapter can be found at:
https://github.com/MauriceNaftalin/JGC_2e_Book_Code/tree/main/src/main/java/org/jgcbook/chapter02
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:
|
is a subtype of |
|
|
is a subtype of |
|
|
is a subtype of |
|
|
is a subtype of |
|
|
is a subtype of |
|
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 also 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. Subtyping is reflexive, meaning that every type is a subtype—and therefore also a supertype—of itself. Every reference type is a ...
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.
Read now
Unlock full access