Bounded type parameters in generics

//Bounded type parameters in generics

Unbounded types vs Bounded Types :

Unbounded Types :

If there is no restriction to the types that can be used as type arguments in a parameterized type then such types are called Unbounded Types.
As the type parameter we can pass any type. Example:

Bounded Types :

As the type parameter we can not pass any type, there are restrictions, we can bound type parameter to a particular parameter and range by using extends keyword, such types are called Bounded Types.

Syntax :

  1. X can be a class or interface.
  2. If X is a class then as a type parameter we can use either X type or its child classes.
  3. If X is interface then as a type parameter we can use either X type or its implementation class Type.

Multiple Bounds :

The preceding examples illustrates the use of a type parameter with a single bound, but a type parameter can have multiple bounds.

  1. A type variable with multiple bounds is a subtype of all the types listed in the bound. If one of the bounds is a class, it must be specified first.
    If bound A is not specified first, you get a compile-time error.
  2. we can take any number of interfaces.
  3. Only one class is allow to use as type parameter and that class must be first and then followed by interface(s).

For example:

Note : In the bounded types we are not allowed to use implements and super keywords.
Bounded Types Demo Example :


Leave A Comment