Many times it will be useful to limit the types that can be passed to type parameters. For that purpose, bounded types are introduced in generics.
Bounded Types
• While
creating objects to generic classes we can pass any derived type as type
parameters.
• Many
times it will be useful to limit the types that can be passed to type
parameters. For that purpose, bounded types are introduced in generics.
• Using
bounded types, we can make the objects of generic class to have data of
specific derived types.
• For
example, If we want a generic class that works only with numbers (like int,
double, float, long .....) then declare type parameter of that class as a
bounded type to Number class. Then while creating objects to that class you
have to pass only Number types or it's subclass types as type parameters.
The
syntax for declaring Bounded type parameters is
<T
extends SuperClass>
• This
specifies that 'T' can only be replaced by 'SuperClass' or it's sub classes.
• For
example
class
Test<T extends Number> //Declaring Number class as upper bound of T
{
T t;
public
Test(T t)
{
this.t =
t;
}
public T
getT()
{
return
t;
}
}
public
class BoundedTypeDemo
{
public static
void main(String[] args)
{
//Creating
object by passing Number as a type parameter
Test<Number>
obj1 = new Test<Number>(123);
System.out.println("The
integer is: "+obj1.getT());
//While
Creating object by passing String as a type parameter, it gives compile time
//error
Test<String>
obj2: = new Test<String>("I am string"); //Compile time error
System.out.println("The
string is: "+obj2.getT());
}
}
Review
Question
1.
Explain the use of bounded types in Generics with illustrative program.
Object Oriented Programming: Unit IV: I/O, Generics, String Handling : Tag: : with Example Java Programs - Bounded Types
Object Oriented Programming
CS3391 3rd Semester CSE Dept | 2021 Regulation | 3rd Semester CSE Dept 2021 Regulation