Let's explore some Java basics - today, bounded type parameters or "What the ... does `<T extends Number>` mean?" Also, "When do (not) I use them?" 🧵 (If you prefer video, it just so happens that I published one on the topic yesterday: youtube.com/watch?v=9rF67I… 😁) 1/7
Whenever you put `<T>` (or any such term) behind a type's declaration or before a method's return type, you *declare* a type parameter. Written like that, every type can be used as a `T` from `Object` all the way down to `String` and `Integer`. Interfaces as well, of course. 2/7
For many cases, particularly collections or other data structures, that's fine. But sometimes you want to interact with the instances handed to your generic class. Maybe you want to execute `Runnable`s or compare `Comparable`s. Then what? 3/7
This is where type parameter bounds come in. Instead of just writing `<T>` you can define types it must extend: * `<T extends Runnable>` only accepts types for `T` that implement `Runnable`. * `<T extends Comparable<T>>` only accepts types for `T` that are `Comparable<T>` 4/7
Combinations work, too: * `<T extends Runnable & Comparable<T>>` only accepts types for `T` that implement both interfaces. That means wherever you use an instance of `T`, the compiler knows it will be `Runnable`, `Comparable<T>`, or whatever else you define as bounds. 5/7