Bounded type
- Java course
- Intermediate
- Lesson 84/116
- 5 min
Learn bounded types with <T extends Number>.
Bounded type parameter
Sometimes you want to restrict a type parameter to a subtype of a specific type. A bounded type does this: writing <T extends Number> means T can only be Number or a subclass of it.
This lets you call Number methods on T; for example num.doubleValue(). Without a bound you cannot know which methods T has; only Object methods are available. Bounded types make generic code more powerful.
Calling Number methods
Thanks to a bounded type you can call the bound's methods on T. With <T extends Number> you can call num.doubleValue() and num.intValue() on a T num variable.
For example static <T extends Number> double toDouble(T num) { return num.doubleValue(); } accepts Integer, Double, Long and other Number subtypes. Without the bound <T> the doubleValue() call would not compile because T being a Number would not be guaranteed.
Practice Write the toDouble generic method
Define the static <T extends Number> double toDouble(T num) generic method whose body is return num.doubleValue();. In main, call it with System.out.println(toDouble(42));.
Starter code
// Define the toDouble generic method (T extends Number)
// main: call toDouble and printlnSample solution
public class Main {
static <T extends Number> double toDouble(T num) {
return num.doubleValue();
}
public static void main(String[] args) {
System.out.println(toDouble(42));
}
}Expected output
42.0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the bounded type declaration
class Stats____ {
T value;
Stats(T value) { this.value = value; }
}
class Stats<T extends Number> {
T value;
Stats(T value) { this.value = value; }
}
Explanation: <T extends Number> bounds T to Number.
2 What does <T extends Number> enable?
- Calling Number methods on T Correct answer
- Making T final
- Making T an interface
- Making T a primitive type
Explanation: The bound lets you call Number methods on T.
3 Match the bounded type concepts
| Term | Meaning |
|---|---|
<T extends Number> |
Bounded type |
extends |
Upper bound keyword |
doubleValue() |
Number method |
<T> |
Unbounded type parameter |