Generics
Bounded Types
Sometimes it is useful to limit the types that can be passed to a
type parameter. For example, a generic class that contains a method that
returns the average of an array of numbers needs to restrict the data types to
numeric data types only (integers, floats, and doubles). To handle such
situations, Java provides bounded types. When specifying a type parameter,
create an upper bound that declares the superclass from which all type
arguments must be derived. This is accomplished through the use of an extends
clause and / or interface type when specifying the type parameter, as shown
here:
<T extends superclass>
<T extends superclass & interface>
// Generic programming
// Arrays - Bounded types
class Gen<T1 extends Number>
{
T1 x[];
Gen(T1 []v1)
{
x = v1;
}
public void fnDisplay()
{
System.out.println("Array
elements");
for(int i =
0;i<x.length;i++)
System.out.println(x[i]);
}
public void fnAvg()
{
double sum = 0;
for(int i =
0;i<x.length;i++)
sum +=
x[i].doubleValue();
System.out.println("Sum
of elements = "+sum);
System.out.println("Average
of elements = "+(sum/x.length));
}
}
class GenPgm4
{
public static void
main(String as[])
{
Integer [] ia =
{2,4,6,8};
Gen<Integer> g1
= new Gen<Integer>(ia);
g1.fnDisplay();
g1.fnAvg();
}
}
No comments:
Post a Comment
Don't be a silent reader...
Leave your comments...
Anu