Powered by Blogger.

Bounded Type Parameters in Java Generics

When you want to restrict the types that can be used as a type arguments in a parameterized type. Then you have to use bounded type parameters. Let us consider the following example. See how bounded type parameter is declared. Type parameter "U" followed by "extends" keyword, then followed by its upper bound (java.lang.Number)

BoundedTypeExample.java:

Output:

T: java.lang.Integer
U: java.lang.Integer

Consider the following code sneppet, since our invocation of inspect includes string, the compilation fails and results in error.

BoundedTypeExample integerClazz = new BoundedTypeExample();
integerClazz.setT(new Integer(10));
integerClazz.inspect(new Integer(20));
integerClazz.inspect("some string"); //ERROR::

ERROR:

Exception in thread "main" java.lang.Error: Unresolved compilation problem
Bound mismatch: The generic method inspect(U) of type BoundedTypeIntro is not applicable for the arguments (String). The inferred type String is not a valid substitute for the bounded parameter

Summary:

Bounded type parameters allows you to do the following:

  • Allows you to limit the types that you are using as a type arguments while instantiating a generic type.
  • Also it allows you to invoke methods defined in the bounds.
To give an example for the second point above consider the following sample code:

EvenOddNumber.java:

Output:

Number 10 is :even number

0 comments:

Post a Comment