Generics and Bounded types
Generics
Generics means parameterized types.
Parameterized types enable users to create classes, interfaces, and
methods in which the type of data upon which they operate is specified as a
parameter.
Using generics, it is possible to create classes that automatically
work with different types of data.
A class, interface, or method that operates on a parameterized type
is called generics.
// Generic programming –
Example
// T1 – Type Parameter
// T1 – will be replaced
by real type when object is created
class Gen<T1>
{
T1 x;
Gen(T1 v)
{
x = v;
}
public void fnDisplay()
{
System.out.println("x
= "+x);
System.out.println("Data
type = "+x.getClass().getName());
}
}
class Generics_Demo
{
public static void
main(String as[])
{
Gen<Integer> g1
= new Gen<Integer>(5);
g1.fnDisplay();
Gen<Double> g2
= new Gen<Double>(4.5);
g2.fnDisplay();
Gen<String> g3
= new Gen<String>("asd");
g3.fnDisplay();
}
}
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 Generics_Demo
{
public static void
main(String as[])
{
Integer [] ia =
{2,4,6,8};
Gen<Integer> g1
= new Gen<Integer>(ia);
g1.fnDisplay();
g1.fnAvg();
}
}