Bounded Types with Generics in Java
There may be times when you want to restrict the types that can be used as type arguments in a parameterized type. For example, a method that operates on numbers might only want to accept instances of Numbers or their subclasses. This is what bounded type parameters are for.
- Sometimes we don’t want the whole class to be parameterized. In that case, we can create a Java generics method. Since the constructor is a special kind of method, we can use generics type in constructors too.
- Suppose we want to restrict the type of objects that can be used in the parameterized type. For example, in a method that compares two objects and we want to make sure that the accepted objects are Comparables.
- The invocation of these methods is similar to the unbounded method except that if we will try to use any class that is not Comparable, it will throw compile time error.
How to Declare a Bounded Type Parameter in Java?
- List the type parameter’s name,
- Along with the extends keyword
- And by its upper bound. (which in the below example c is A.)
<T extends superClassName>
Note that, in this context, extends is used in a general sense to mean either “extends” (as in classes). Also, This specifies that T can only be replaced by superClassName or subclasses of superClassName. Thus, a superclass defines an inclusive, upper limit.
Let’s take an example of how to implement bounded types (extend superclass) with generics.
Inside sub class C Inside sub class B Inside super class A
Now, we are restricted to only type A and its subclasses, So it will throw an error for any other type of subclasses.
error: type argument String is not within bounds of type-variable T
Bounded type parameters can be used with methods as well as classes and interfaces.
Java Generics supports multiple bounds also, i.e., In this case, A can be an interface or class. If A is class, then B and C should be interfaces. We can’t have more than one class in multiple bounds.
<T extends superClassName & Interface>
Inside super class A
This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.