Bounded Type Parameters
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 Number or its subclasses. This is what bounded type parameters are for.
- Sometimes we don’t want whole class to be parameterized, in that case we can create java generics method. Since 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 unbounded method except that if we will try to use any class that is not Comparable, it will throw compile time error.
Declare a bounded type parameter
- List the type parameter’s name.
- Along by the extends keyword
- And by its upper bound.(which in below example 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, superclass defines an inclusive, upper limit.
Let’s take an example on how to implement bounded types (extend superclass) with generics.
Inside sub class C Inside sub class B Inside super class A
Now, we restricted to only of type A and its sub classes, So it will throw an error for any other type or sub classes.
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
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
This article is attributed to GeeksforGeeks.org